我在使用 React 时遇到了一些奇怪的事情。
class C extends React.Component {
componentDidMount = this.animate; // <---
animate = () => ...
}
这没有用,所以我不得不更改 componentDidMount 的值并且它起作用了:
class C extends React.Component {
componentDidMount = () => this.animate(); // Lambda is required?
animate = () => ...
}
有人能很好地解释为什么需要这样做吗?
最佳答案
如果你写
class C extends React.Component {
componentDidMount = this.animate; // <---
animate = () => ...
}
然后 componentDidMount
被设置为 undefined
因为当时没有设置 animate
使用 componentDidMount = () => this.animate();
this.animate();
每次 componentDidMount
都会解析调用,这就是为什么这对你有用。
如果你这样写:
class C extends React.Component {
animate = () => ...
componentDidMount = this.animate; // <---
}
然后 componentDidMount
将引用您之前分配给 animate
的功能。
但是如果你想为一个类定义方法你应该检查baao的答案,因为这样你就不应使用赋值,而应使用方法定义 animate() {}
关于javascript - 奇怪的类属性行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40819697/