[英]Why getters don't have access to state in React components?
Trying to get access to the component state from a getter, I noticed that this
is set to a different context than in a normal method and therefore this.state
doesn't work. 试图从getter访问组件状态,我注意到
this
被设置为与普通方法不同的上下文,因此this.state
不起作用。
See here: http://jsfiddle.net/tkaby7ks/ 见这里: http : //jsfiddle.net/tkaby7ks/
Why is that and how can I get access to the state from a getter? 为什么这样,我如何从getter访问状态?
The point is that the getter is a property of the object you pass to React.createClass
, not of the class that is created: react treats it as a value. 关键是getter是传递给
React.createClass
的对象的属性,而不是创建的类的属性:react将其视为值。 From reacts perspective, the following 2 code snippets are exactly the same: 从反应的角度来看,以下两个代码片段完全相同:
var MyComponent = React.createClass({
foo: "asdf",
...
})
vs. 与
var MyComponent = React.createClass({
get foo() { return "asdf" },
...
})
For functions that you pass to createClass
, react binds the this
variable to the component, but for getters it is not possible. 对于传递给
createClass
函数,react this
变量绑定到组件,但对于getter,则不可能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.