好
this
而课堂是你最难理解的科目之一。也许通过几个例子更容易理解。
看看
this issue
在React存储库中。丹·阿布拉莫夫解释了Facebook内部使用的方法。
class MyComponent extends React.Component {
name = 'MyComponent';
constructor(props) {
super(props);
this.handleClick4 = this.handleClick4.bind(this);
}
handleClick1() {
// `this` is not the component instance since this function isn't bound to this class instance.
alert(this.name); // undefined
}
handleClick2() {
// Using arrow functions we force the context to this component instance.
alert(this.name); // MyComponent
}
handleClick3 = () => {
// Instead of using class methods, we assign an Arrow function to as a member of this class instance.
// Since arrow functions are bound automatically to the current context, it's bound to this class instance.
alert(this.name); // MyComponent
};
handleClick4() {
// We are actually overriding this property with a "bound" version of this method in the constructor.
alert(this.name); // MyComponent
}
render() {
return (
<div>
<button onClick={this.handleClick1}>click 1</button>
<button onClick={() => this.handleClick2}>click 2</button>
<button onClick={this.handleClick3}>click 3</button>
<button onClick={this.handleClick4}>click 4</button>
</div>
);
}
}