我使用React并碰到了一些奇怪的东西。
class C extends React.Component {
componentDidMount = this.animate; // <---
animate = () => ...
}
这不起作用所以我不得不更改componentDidMount的值并且它有效:
class C extends React.Component {
componentDidMount = () => this.animate(); // Lambda is required?
animate = () => ...
}
有没有人能够很好地解释为什么需要这样做?
答案 0 :(得分:2)
如果你写
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() {}
答案 1 :(得分:2)
您应该将animate方法定义为类方法,而不是箭头函数。
class C extends React.Component {
componentDidMount = this.animate;
animate() {}
}