我已阅读 React Docs关于构造函数方法及其在设置状态和绑定(bind)函数方面的用途,但在大多数情况下真的有必要吗?
做和做有什么区别
export default class MyClass extends Component {
constructor(props) {
super(props);
this.state = {
foo: 'bar',
};
this.member = 'member';
this.someFunction = this.anotherFunction(num);
}
anotherFunction = (num) => num * 2;
render() {
// render jsx here
}
}
然后简单地将所有这些放在构造函数之外
export default class MyClass extends Component {
state = {
foo: 'bar',
};
member = 'member';
someFunction = this.anotherFunction(num);
anotherFunction = (num) => num * 2;
render() {
// render jsx here
}
}
是否有一个选项优于另一个选项?是否有任何我应该了解的性能问题?这一直困扰着我,我似乎找不到具体的答案。
最佳答案
你的两个例子在功能上是相同的,但关键是在类方法之外分配东西,但在类的主体内部,就像除了 render
和 之外的所有东西constructor
,不是标准的 ES6,只能通过 Babel 工作。该语法是建议的 class property syntax .
关于javascript - React 中的构造方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43815236/