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>