如何优雅地在React中处理事件响应&&React绑定onClick为何要用箭头函数?

React绑定onClick为何要用箭头函数?es6

https://segmentfault.com/q/1010000010918131segmentfault

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

https://segmentfault.com/a/1190000010308456this

一:code

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

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

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

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

二:bind

onClick内部使用箭头函数

箭头函数能够自动绑定定义此函数做用的this,所以不须要bind

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

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

相关文章
相关标签/搜索