Why do I have to .bind(this) for methods defined in React component class, but not in regular ES6 class

前端 未结 5 1805
感动是毒
感动是毒 2020-11-27 16:57

Something that is puzzling me is why when I define a react component class, values contained in the this object are undefined in methods defined (this

5条回答
  •  被撕碎了的回忆
    2020-11-27 17:09

    Event handlers in the component will not be bound automatically to the component instance like other methods ( life cycle methods...).

    class MyComponent extends React.Component {
       render(){
          return (
             
    {this.renderElements()} <-- `this` is still in side the MyComponent context
    ) } } //under the hood var instance = new MyComponent(); var element = instance.render(); //click on div element.onClick() <-- `this` inside renderElements refers to the window object now

    Check this example to understand this more :

    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
    

    You can check this article for more information.

提交回复
热议问题