反应将此绑定到类方法 [英] React binding this to a class method
问题描述
所以我正在读一本关于React的书,说我必须像
So i'm reading a book on React which said I have to bind my methods like
this.onClickMe = this.onClickMe.bind(this);
但是看起来不用上面的代码就可以正常工作
but it looks to work just fine without using the above code
class ExplainBindingsComponent extends Component {
onClickMe() {
console.log(this);
}
render() {
return (
<button
onClick={ () => { this.onClickMe() } }
type="button"
>
Click Me
</button>
);
}
}
但这是说我应该做这样的事情,
but it's saying I should do something like this,
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);
还是我必须要做的事情吗?如果可以的话,与上面的示例相比,该怎么做
is this.onClickMe = this.onClickMe.bind(this);
still something I have to do? and if so what does it do vs my above example
推荐答案
有多种方法可以将函数绑定到React类的词法上下文
There are multiple ways to bind your function to the lexical context of the React class,
-
一种这样的方法是将其绑定到构造函数中,
one such method is to bind it in the constructor,
另一种方法是将类字段用作箭头函数,并且
other method is to use class fields as arrow functions, and
可以使用其中的每一个,但是最好避免在渲染中绑定,因为每个渲染都会返回一个新函数
Each of these can be used, however its best to avoid binding in the render since a new function is returned on each render
使用类字段作为箭头功能.
Using class field as arrow function.
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)}
这篇关于反应将此绑定到类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!