bind(this)的原因
- 在
JavaScript
中,class
内定义的方法默认情况下不会绑定this
,所以我们要使用bind()手动绑定this,使this时刻指向组件本身
其他绑定this的方法
定义时绑定
1
2
3
4
5// 此语法确保 `handleClick` 内的 `this` 已被绑定。
// 注意: 这是 *实验性* 语法。
handleClick = () => {
console.log('this is:', this);
}调用时绑定
1
2
3
4
5
6
7
8render() {
// 此语法确保 `handleClick` 内的 `this` 已被绑定。
return (
<button onClick={(e) => this.handleClick(e)}>
Click me
</button>
);
}