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

前端 未结 5 1742
感动是毒
感动是毒 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:05

    Just always put the autoBind(this); code in your constructor and never worry about method pointers.

    npm install --save auto-bind-inheritance

    const autoBind = require('auto-bind-inheritance');
    
    class Animal {
      constructor(name) {
        autoBind(this);
        this.name = name;
      }
    
      printName() { console.log(this.name); }
      ...
    }
    
    let m = new Animal('dog');
    let mpntr = m.printName;
    m.printName() //> 'dog'
    mpntr()       //> 'dog', because auto-bind, binds 'this' to the method.
    

提交回复
热议问题