令我感到困惑的是,为什么当我定义 React 组件类时,this
对象中包含的值在类中定义的方法中未定义(this
在生命周期方法中可用),除非我使用.bind(this)
或使用箭头函数定义方法,例如在下面的代码this.state
在renderElements
函数中将是未定义的,因为我没有用箭头函数定义它,也没有使用.bind(this)
class MyComponent extends React.Component {
constructor() {
super();
this.state = { elements: 5 }
}
renderElements() {
const output = [];
// In the following this.state.elements will be undefined
// because I have not used .bind(this) on this method in the constructor
// example: this.renderElements = this.renderElements.bind(this)
for(let i = 0; i < this.state.elements; i ++){
output.push(<div key={i} />);
}
return output;
}
// .this is defined inside of the lifecycle methods and
// therefore do not need call .bind(this) on the render method.
render() {
return (
<div onClick={this.renderElements}></div>
);
}
}
然后在下面的例子中我不需要使用.bind(this)
或箭头函数,this
在speak
函数中按预期可用
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Dog extends Animal {
speak() {
console.log(this.name + ' barks.');
}
}
var d = new Dog('Mitzie');
d.speak();
http://jsbin.com/cadoduxuye/edit?js,console
澄清一下,我的问题分为两部分。一)为什么在第二个代码示例中我不需要调用.bind(this)
该speak
函数,但我在 React 组件中renderElements
调用该函数,二)为什么生命周期方法(render、componentDidMount 等)已经可以访问该类'this
反对,但renderElements
没有。
在 React 文档中,它说以下内容
[React Component Class] 方法遵循与常规 ES6 类相同的语义,这意味着它们不会自动将 this 绑定到实例。
但很明显他们这样做了,正如我发布的第二个代码示例所示。
更新
前两条评论中的两个链接都显示了一个未.bind(this)
在类方法上使用的 React 类的工作示例,并且工作正常。但仍然在文档中明确表示您需要绑定您的方法,或使用箭头函数。在使用 gulp 和 babel 的项目中,我可以重现。这是否意味着浏览器更新了东西?
更新 2
我的初始代码示例this.renderElements()
直接在渲染函数中调用。这将按预期工作,无需绑定函数或使用箭头函数定义它。当我将该函数作为onClick
处理程序时会出现问题。
更新 3
当我将该函数作为
onClick
处理程序时会出现问题。
事实上,这根本不是问题。this
传递给 onClick 处理程序时更改的上下文,这就是 JS 的工作方式。