在新的 React ES6 类中,this
需要按照此处所述进行绑定(bind):http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding
例如:
class Counter extends React.Component {
constructor() {
super();
this.tick = this.tick.bind(this);
}
tick() {
...
}
...
}
对此的解释是因为它是默认行为,但是如果我创建一个 ES6 类,然后创建它的一个新实例,this
将被绑定(bind)
import React from 'React'
class Test extends React.Component {
constructor() {
super()
}
foo () {
console.log('bar')
}
hello() {
this.foo()
}
}
var test = new Test()
test.hello()
// > bar
为什么 React 需要绑定(bind)?
最佳答案
您需要为方法设置 this
以防万一,例如,如果您需要将函数引用传递给事件处理程序,但是您不需要为每个方法都设置 this
.,
class Counter extends React.Component {
constructor() {
super();
this.tick = this.tick.bind(this);
}
tick() {
// this refers to Counter
}
fn() {
// this refers to Counter
}
withoutBind() {
// this will be undefined or window it depends if you use "strict mode" or not
}
render() {
this.fn(); // this inside this method refers to Counter
// but if you will do like this
const fn = this.fn;
fn(); // this will refer to global scope
return <div>
<button onClick={this.tick}>1</button>
<button onClick={this.withoutBind}>2</button>
</div>;
}
}
关于javascript - 为什么在 ES6 react 类中需要绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36309636/