我已经阅读了关于构造函数方法的React,以及它可以用于设置状态和绑定函数的内容,但是在大多数情况下它真的是必要的吗?
做这种事有什么区别
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
}
}一种选择是否优先于另一种选择,以及是否存在任何我应该知道的性能问题?这已经困扰了我一段时间了,我似乎找不到一个具体的答案。
发布于 2017-05-06 00:19:33
您的两个示例在功能上是相同的,但是关键是在类方法之外,但是在类的主体内分配东西,就像您对render和constructor以外的所有东西一样,不是标准的ES6,只能通过Babel来工作。这个语法就是建议的类属性语法。
https://stackoverflow.com/questions/43815236
复制相似问题