在react中例如onClick事件绑定函数时会有‘this’的指向问题这里举例几种解决方案
1
handleFunctionName(){
// something
}
render(){
return (
<button onClick="(e)=>{this.handleFunctionName(e)}">Click</button>
)
}
2
constructor(props) {
this.handleFunctionName = this.handleFunctionName.bind(this)
}
handleFunctionName(){
// something
}
render(){
return (
<button onClick="{this.handleFunctionName()}">Click</button>
)
}
3
handleFunctionName=(e)=>{
// something
}
render(){
return (
<button onClick="{this.handleFunctionName()}">Click</button>
)
}
4.
handleFunctionName(){
// something
}
render(){
return (
<button onClick="{this.handleFunctionName().bind(this)}">Click</button>
)
}
Comments | NOTHING