React绑定onClick为什么要用箭头函数?

https://segmentfault.com/q/1010000010918131

如何优雅地在React中处理事件响应

https://segmentfault.com/a/1190000010308456

一:

事件处理函数使用es6写法:

在使用ES6 classes或者纯函数时,React不会自动绑定this到当前组件上,需要手动实现this的绑定。

handleClick = (i) => {
console.log(i)
}

<p onClick={this.handleClick.bind(this,123)}>iiiii</p>

二:

onClick内部使用箭头函数

箭头函数可以自动绑定定义此函数作用的this,因此不需要bind

testhhandleClick(){
console.log('testhhandleClick')
}

<p onClick={()=>{this.testhhandleClick()}}>testhhandleClick</p>

 

相关文章:

  • 2021-11-02
  • 2022-12-23
  • 2022-12-23
  • 2021-08-08
  • 2021-12-03
  • 2022-12-23
  • 2021-12-26
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案