Class中的this指针与React

我们知道React中的Class组件,其事件处理函数要么bind(this),要么用箭头函数( ()=>{...} ),否则this指针会是undefined

原因如下:

class Logger {
  printName(name = 'there') {
    this.print(`Hello ${name}`);
  }

  print(text) {
    console.log(text);
  }
}

const logger = new Logger();
const { printName } = logger;
printName(); // TypeError: Cannot read property 'print' of undefined

以上示例代码中如果执行logger.printName(), this指向的是Logger类的实例logger。 而如果单独执行printName(),则this指向的是全局对象,而class默认严格模式,所以this的值是undefined
要想改变,必须这么做:

class Logger {
  constructor() {
    this.printName = this.printName.bind(this);
  }

  // ...
}

绑定printName函数的上下文环境到this(类的实例)

参考:
https://es6.ruanyifeng.com/#docs/class
https://blog.csdn.net/qq_34829447/article/details/81705977

posted @ 2020-11-19 20:52  老胡Andy  阅读(220)  评论(0编辑  收藏  举报