所以我正在读一本关于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);仍然是我必须做的?如果可以的话,与上面的例子相比,它能做什么
有多种方法可以将函数绑定到React类的词法上下文,
一种这样的方法是将其绑定到构造函数中,
另一种方法是将类字段用作箭头函数,并且
使用.bind或arrow在渲染中绑定的第三种方法,
每个都可以使用,但是最好避免在渲染中绑定,因为每个渲染都会返回一个新函数
使用类字段作为箭头功能。
class ExplainBindingsComponent extends Component { onClickMe = () => { console.log(this); } render() { return ( <button onClick={ this.onClickMe } type="button" > Click Me </button> ); } }
绑定渲染
onClick={() => this.onClickMe() }
要么
onClick={this.onClick.bind(this)}