react中解决this指向问题的四种方法
一.行间定义事件后面使用bind绑定this
run(){
alert("第一种方法!")
}
<button onClick={this.run.bind(this)}>第一种</button>
二.在构造函数内部声明this指向
constructor(props) {
super(props);
this.state={
//定义数据
}
this.run = this.run.bind(this);
}
run(){
alert("第二种方法!")
}
<button onClick={this.run}>第二种</button>
三.声明事件时将事件等于一个箭头函数
run=()=> {
alert("第三种方法!")
}
<button onClick={this.run}>第三种</button>
四.行间定义事件使用箭头函数
run(){
alert("第四种方法!")
}
<button onClick={()=>this.run()>第四种</button>