【react】react事件绑定函数 ‘this’的指向问题解决方案


在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>
  )
}

声明:麋鹿与鲸鱼|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - 【react】react事件绑定函数 ‘this’的指向问题解决方案


Carpe Diem and Do what I like