我们可以在类构造函数中绑定我们的事件处理程序:
我们现在可以在事件句柄中访问它
class MyClass extends Component {
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
}
handleChange(){
//you can now access "this" inside handlechange
}
}
看起来不错。当我们向我们的类添加更多事件处理程序时,代码应该如下所示:
import React, { Component } from 'react'
import { MyInput, MyAnotherInput } from 'myInputs'
class MyComponent extends Component {
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.handleClick = this.handleClick.bind(this)
this.handleKeyPress = this.handleKeyPress.bind(this)
}
handleChange(e) {
e.preventDefault()
}
handleClick(e) {
e.preventDefault()
}
handleKeyPress(e) {
e.preventDefault()
if (e.nativeEvent.keyCode === 13) {
console.log('This is enter!')
}
}
render() {
return (
<div>
<MyInput
onChange={ this.handleChange }
onClick={ this.handleClick }
onKeyPress={ this.handleKeyPress }
/>
<MyAnotherInput
onChange={ this.handleChange }
onClick={ this.handleClick }
onKeyPress={ this.handleKeyPress }
/>
</div>
)
}
}
这就是,我们可以使用 es2015 作为预设配置的 Babel 编译器。
带有箭头函数的事件处理程序
您可能已经看到,当我们创建事件处理方法时,我们总是需要将 this 添加到构造函数中,以绑定 this。挺累的。老实说,仅仅为了绑定你的方法而创建构造方法是没有意义的。应该有另一种解决方案,而且确实有。
您只需要安装 stage-1 Babel 预设并使用箭头功能。如果你不知道怎么做,去 Babel 文档,很好。
在我们的例子中,我们可以这样写而不是绑定方法:
render() {
return(<MyInput onChange={ (e) => this.handleOnChange(e) } />)
}
我们创建了新的匿名函数,它会自动绑定 this,
这就是我们不需要使用 .bind() 方法的原因。我们还是一样
类中的方法,以及新的箭头函数作为回调中的包装器
属性。
这仍然不是完美的解决方案,因为我们需要更新箭头函数包装器中的参数,并且每次触发渲染方法时都会创建新实例。 React 属性中的箭头函数也不是个好主意。