【发布时间】:2017-04-10 17:21:03
【问题描述】:
我正在使用 React,但遇到了一些奇怪的事情。
class C extends React.Component {
componentDidMount = this.animate; // <---
animate = () => ...
}
这不起作用,所以我不得不更改 componentDidMount 的值并且它起作用了:
class C extends React.Component {
componentDidMount = () => this.animate(); // Lambda is required?
animate = () => ...
}
有人对为什么需要这样做有很好的解释吗?
【问题讨论】:
-
可能
animate内部使用this,当通过this.animate()调用时与通过对animate的函数引用时会有所不同。而是尝试:componentDidMount = this.animate.bind(this)绑定thisArg -
我认为这不是问题,因为第二个代码 sn-p 运行良好
-
这表明调用实际上是问题所在,所以我的建议应该有效。显示
this.animate函数的内容 -
我展示的只是一个例子。我想知道的是为什么这两个代码 sn-ps 不等价
-
请注意,类属性不是 ES6 的一部分。
标签: javascript reactjs ecmascript-6 ecmascript-next