我对如何在ES6构造函数中使用this感到困惑。
首先,我理解了以下内容(参见下面的示例):-我们使用this.height = height;添加一个新的instance variable。
className() {...}添加一个新的实例方法,并使用getter this添加一个静态类来引用下面的getter中的实例方法,如this.calcArea()。class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() { // Getter
return this.calcArea();
}
calcArea() {
return this.height * this.width;
}
static staticMethod() {
return 'static method has been called.';
}
}然而,当我看到下面附加的React示例时,ln-7中的this.handleClick = this.handleClick.bind(this);让我感到困惑。我理解this.handleClick.bind(this);的意思。我怀疑的部分是this.handleClick,它位于=标志的LEFT一侧。this.handleClick看起来像是在做一个名为handleClick的instance variable。在前面的例子中,我用this.height = height;的b/c的方式来看待它。
我的问题是:我的想法错了吗?或者谁能解释一下=标志的LEFT端的this.handleClick是做什么的?

发布于 2019-05-15 22:27:02
用于将函数绑定到组件实例上。请查看here。它用于ES5函数。如果你使用了ES6函数,你就不需要使用find了。
class Foo extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this); // need binding for es5
}
handleClick() {
console.log('Click happened');
}
handleClick2 = () => {
console.log('click happened (es6)');
}
render() {
return (
<div>
<button onClick={this.handleClick}>Click Me</button>
<button onClick={this.handleClick2}>Click Me 2</button>
</div>
);
}
}注意: this关键字用于在基本javascript类的情况下为对象实例赋值。类似地,它被用于react类。
https://stackoverflow.com/questions/56151531
复制相似问题