所以我正在读一本关于 React 的书,上面说我必须像这样绑定我的方法
this.onClickMe = this.onClickMe.bind(this);
但它看起来在不使用上面的代码的情况下工作得很好
class ExplainBindingsComponent extends Component {
onClickMe() {
console.log(this);
}
render() {
return (
<button
onClick={ () => { this.onClickMe() } }
type="button"
>
Click Me
</button>
);
}
}
但它说我应该做这样的事情,
class ExplainBindingsComponent extends Component {
constructor() {
super();
this.onClickMe = this.onClickMe.bind(this);
}
onClickMe() {
console.log(this);
}
render() {
return (
<button
onClick={this.onClickMe}
type="button"
>
Click Me
</button>
);
}
}
是 this.onClickMe = this.onClickMe.bind(this);
还是我必须做的事情?如果是的话,它与我上面的例子相比有什么作用
原文由 user6427229 发布,翻译遵循 CC BY-SA 4.0 许可协议
有多种方法可以将你的函数绑定到 React 类的词法上下文,
一种这样的方法是在构造函数中绑定它,
另一种方法是使用类字段作为箭头函数,并且
使用 .bind 或箭头在渲染中绑定的第三种方法,
这些中的每一个都可以使用,但是最好避免在渲染中绑定,因为每个渲染都会返回一个新函数
使用类字段作为箭头函数。
在渲染中绑定
或者