修改this指向
- bind 方式绑定
- 函数通过箭头函数进行创建
- constructor提前绑定
- 把事件的调用写成箭头函数的调用方式
<div id="reactDom"></div>
<script type="text/babel">
class Com extends React.Component {
constructor(props){
super(props)
this.myRef = React.createRef();
this.func = this.func.bind(this)
}
funa(){
console.log(this)
}
funb = ()=>{
console.log(this)
}
func(){
console.log(this)
}
fund(){
console.log(this)
}
fune=(i,e)=>{
console.log(i)
console.log(e)
}
render() {
return (
<div>我是组件
<button onClick={this.funa.bind(this)}>bind方式绑定</button>
<button onClick={this.funb}>箭头函数绑定</button>
<button onClick={this.func}>提前绑定</button>
<button onClick={()=>{this.fund()}}>调用方式为箭头函数</button>
<h1>函数实参传递</h1>
<button onClick={this.fune.bind(this,"我是参数")}>点我传递实参</button>
<button onClick={(e)=>{this.fune("我是参数2",e)}}>点我传递实参</button>
</div>
)
}
}
ReactDOM.render(<Com />, document.getElementById("reactDom"))
</script>
条件渲染
条件渲染 — 根据状态的变化只渲染其中的一部分
基本使用
<div id="reactDom"></div>
<script type="text/babel">
// 条件渲染 --- 根据状态的变化只渲染其中的一部分
// if语句 jsx中不允许有if
class Com extends React.Component {
constructor(props) {
super(props)
this.state = {
bool: true
}
}
fun() {
this.setState({
bool:!this.state.bool
})
}
render() {
let text;
if (this.state.bool) {
text = "你好"
} else {
text = "你坏"
}
return (
<div>
我是组件
<button onClick={this.fun.bind(this)}>点我</button>
{text}
<p>三元运算法: {this.state.bool?"呵呵":"哈哈"}</p>
</div>
)
}
}
ReactDOM.render(<Com />, document.getElementById("reactDom"))
</script>
状态提升
- 当多个组件需要同一个变化的数据时,需要把该数据提升到它们的父组件
- 多个组件需要利用到对方的状态的情况下,就需要使用状态提升
<div id="reactDom"></div>
<script type="text/babel">
class Demoa extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div>
我是第一个组件 -- {this.props.text}
</div>
)
}
}
class Demob extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div>
我是第二个组件 -- {this.props.text}
</div>
)
}
}
class Com extends React.Component {
constructor(props) {
super(props)
this.state={
comtext:"我是两个人都想使用的数据"
}
}
fun=()=>{
this.setState({
comtext:"修改数据"
})
}
render() {
return (
<div>
我是组件
<button onClick={this.fun}>修改数据</button>
<Demoa text={this.state.comtext}/>
<Demob text={this.state.comtext}/>
</div>
)
}
}
ReactDOM.render(<Com />, document.getElementById("reactDom"))
</script>