类组件需要绑定事件的原因
class EventBind extends React.component {
constructor(props) {
super(props)
}
onPress() {
console.log('this: ', this) // undefined
}
render() {
return <button onClick={this.onPress}>display</button>
}
}
方式
- 使用bind()绑定this
class EventBind extends React.component {
constructor(props) {
super(props)
}
onPress() {
console.log('this: ', this) //
}
render() {
// 方案一:在render函数中使用bind()
return <button onClick={this.onPress.bind(this)}>display</button>
}
}
class EventBind extends React.component {
constructor(props) {
super(props)
// 方案二:在constructor函数中使用bind()
this.onPress = this.onPress.bind(this)
}
onPress() {
console.log('this: ', this)
}
render() {
return <button onClick={this.onPress}>display</button>
}
}
- 使用箭头函数,利用其特性(箭头函数在定义时,会将其上层作用域的this作为自己的this,并且保持不变)绑定this
class EventBind extends React.component {
constructor(props) {
super(props)
}
onPress() {
console.log('this: ', this)
}
render() {
// 方案三:在render函数中使用使用箭头函数
return <button onClick={(e) => this.onPress(e)}>display</button>
}
}
class EventBind extends React.component {
constructor(props) {
super(props)
}
// 方案四:在定义函数时使用箭头函数
onPress = () => {
console.log('this: ', this)
}
render() {
return <button onClick={this.onPress}>display</button>
}
}
区别
方案一:render函数并非只调用一次,有可能会有很多次,每次调用render时都会进行一次事件绑定,这种方式是不合适的,如果一定要使用bind()这种方式进行事件绑定,更推荐方案二
方案三:同理,每次调用render时都需要调用箭头函数来进行this的绑定,因此更推荐方案四,直接在定义函数时依靠箭头函数完成this的绑定。
结论:更加推荐方式二中的方案四,可以优雅的完成事件的绑定,尤其是倘若想简写class组件省略constructor的调用时,用这种方式也能完成事件绑定。