繁体   English   中英

React如何调用ES6类的render函数,使`this`不引用类本身?

[英]How does React call the render function of an ES6 class in a such a way that `this` does not refer to the class itself?

例如,给定具有函数increaseQty的类

increaseQty() {
  this.qty++
}

和电话

render() {
  return (
    <div>
      <button onClick={this.increaseQty}>Increase</button>
    </div>
  )
}

this.qty是不确定的,除非我写我的构造线结合的情况下this在构造函数中的作用

constructor(props) {
  super(props)
  this.qty = 0
  this.increaseQty = this.increaseQty.bind(this) // <---- like so
}

但是,如果您只是正常使用它,那么在正常的es6类中就不是这种情况:

https://jsfiddle.net/omrf0t20/2/

class Test {
  constructor() {
    this.qty = 0
  }

  increaseQty() {
    console.log(++this.qty)
  }

  doStuff() {
    this.increaseQty()
  }
}

const t = new Test()
t.doStuff() // prints 1

哪些方面发生反应使得它使render调用时没有的情况下this

这里的区别是,在你的榜样与之反应你逝去的increaseQty作为回调到另一个组件,但在第二,你是在当前上下文中调用它。

您可以在简化示例中看到差异

class Test {
  constructor() {
    this.qty = 0
  }

  increaseQty() {
    console.log(++this.qty)
  }

  doStuff() {
    this.increaseQty(); // no need to bind
  }

  listenClicks() {
    // you should use bind to preserve context
    document.body.addEventListener('click', this.increaseQty.bind(this)); 
  }
}

React指南还建议您在构造函数中绑定方法,使代码更加优化,绑定一次并始终使用相同的函数,而不是为每个render()调用创建新的绑定版本。

这不是一个特定于ES6的问题(除了我们引用类和构造函数之外)。 你在函数中所做的只是递增一个值。 如果该值尚未初始化为某些内容(即使在ES5中),则会引发错误。 您不能将1添加到undefined

在ES5(和ES6真的)这将是一个问题:

var myObj = {
    addOne: function() {
        this.qty++;
    }
}

myObj.addOne(); // Error! this.qty is undefined

虽然这会解决它:

var myObj = {
    qty: 0,
    addOne: function() {
        this.qty++;
    }
}

myObj.addOne(); // Good to go

你班上的情况也是如此。 您不能将尚未声明和初始化的变量增加到数值。

在一个更简单的例子中:

var x;

x++;

会抛出一个错误,而这个:

var x = 0;

x++;

很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM