组件中的事件处理程序不会像其他方法(生命周期方法…)那样自动绑定到组件实例。
class MyComponent extends React.Component { render(){ return ( <div onClick={this.renderElements}> {this.renderElements()} <-- `this` is still in side the MyComponent context </div> ) }}//under the hoodvar instance = new MyComponent();var element = instance.render();//click on divelement.onClick() <-- `this` inside renderElements refers to the window object now查看此示例以了解
this更多信息:
class Animal { constructor(name) { this.name = name; } speak() { console.log(this.name + ' makes a noise.'); } }class Dog extends Animal { run(){ console.log(this.name + ' runs'); } speak() { console.log(this.name + ' barks.'); this.run(); <-- `this` is still in the Dog context return {onRun : this.run}; }}var d = new Dog('Mitzie');var myDog = d.speak();myDog.onRun() <-- `this` is now in the global context which is the `window` object您可以查看本文以获取更多信息。



