javascript - 奇怪的类属性行为

标签 javascript reactjs ecmascript-6 ecmascript-next

我在使用 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/

相关文章:

javascript - ES6 Class 使得构造函数 "+"能够被使用

javascript - Firefox 和 Chrome - iframe 的不同行为

reactjs - react 。如果展示组件包含容器组件会不会很糟糕?

javascript - 在Vue中,createElement()实际获取哪些参数?

javascript - 获取 React.element 的元素(子元素)

reactjs - React 中的导入对象未定义

javascript - 如何向对象添加新属性?

javascript - 如何在 Ember 中没有 Controller 的情况下更改查询参数?

javascript - 在 AngularJS 模板中增加一个变量

javascript - 评估在 JavaScript 中给出 bool 表达式的字符串