【发布时间】:2016-04-09 03:12:23
【问题描述】:
例如,给定具有函数 increaseQty 的类
increaseQty() {
this.qty++
}
和电话
render() {
return (
<div>
<button onClick={this.increaseQty}>Increase</button>
</div>
)
}
除非我在构造函数中写一行将构造函数中this 的上下文绑定到函数,否则this.qty 将是未定义的
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
React 的什么方面使得 render 在没有 this 上下文的情况下被调用?
【问题讨论】:
-
“这还不是标准” 箭头函数已包含在去年标准化的 ES6 规范中。他们哪儿也不去。
-
@JeremyBanks 你是对的,但这与此无关。我目前正在谈论的是第一阶段提案github.com/jeffmo/es-class-fields-and-static-properties
-
是的,我怀疑是这样的。这就是为什么我想看一个完整的例子。它不一定是only React。但总的来说,使用
class语法创建的方法的行为类似于通过 FunctionName.prototype.methodName =... 创建的老式语法,这意味着除非您使用 .bind() ,否则有几种方法可以更改this的内容将在调用时。 -
(我并不真正了解 React,但我假设)您的 React 渲染调用失败的原因与在任何回调情况下传递对该方法的引用都会失败的原因相同。例如。
setTimeout(this.increaseQty, 10)以同样的方式失败。在 JS 中,“方法”并不真正属于对象,“方法”只是一个引用函数的对象属性,在渲染代码中,您传递的是对函数的引用,而不是对象。 -
这种现象与 React 无关,这只是
this在 JavaScript 中的工作方式。看看MDN page aboutthis。
标签: javascript class reactjs ecmascript-6 this