方案1:把事件绑定到一个匿名函数上
f1(){
console.log('f1......')
}
render() {
return (
<div>
<button onClick={()=>{this.f1()}}>-</button>
<span >{this.count}</span>
<button>+</button>
</div>
)
}
}
方案2:把事件绑定到一个有名的箭头函数上
f1=()=>{
console.log('f1......',this)
this.count--
}
render() {
return (
<div>
<button onClick={this.f1}>-</button>
<span >{this.count}</span>
<button>+</button>
</div>
)
}
}
方案3 事件绑定,通过bind 改变this 指向
f1(){
console.log('f1......',this)
}
<button onClick={this.f1.bind(this)}>-</button>
<span >{this.count}</span>
<button>+</button>
方案4:在构造方法中固定this的指向 —————官网手册用的此方法
constructor(props){
super(props)
console.log('app的constructor',this)
this.f1=this.f1.bind(this)
}
f1(){
console.log(this)
}
<button onClick={this.f1}>-</button>
<span >{this.count}</span>
<button>+</button>
本文介绍了四种解决React事件处理函数中this指向问题的方法:使用匿名函数、有名箭头函数、bind方法以及在构造函数中绑定。这些方案旨在确保在事件处理中正确访问组件实例。
129

被折叠的 条评论
为什么被折叠?



