调用方法1公共类字段语法 https://babeljs.io/docs/en/babel-plugin-proposal-class-properties,使用它我们不需要担心它的含义this
在运行时,因为它是自动绑定的。例如:
class LoggingButton extends React.Component {
// This syntax ensures `this` is bound within handleClick.
// Warning: this is *experimental* syntax.
handleClick = () => {
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}
}
在方法 2 中,它只是类中的一个普通方法,当您使用ES6级 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
不过,在使用这种方法的时候,你必须要小心它的含义this
在 JSX 回调中。在 JavaScript 中,类方法不是bound https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind默认情况下。如果忘记绑定this.handleClick
并将其传递给onClick
, this
将不明确的当函数被实际调用时。
class LoggingButton extends React.Component {
constructor(props) {
super(props);
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('this is:', this);
}
render() {
return <button onClick={this.handleClick}>Click me</button>;
}
}
方法1和方法2的区别在于:this
当函数被实际调用时,在函数内部。
参考:处理事件 https://reactjs.org/docs/handling-events.html