最近我开始学习 ReactJS,因此开始学习 ES6。我对 ES5 很熟悉,但有些事情对我来说不是那么清楚。
示例 1:方法语法
下面两种方法有什么区别?
export class InvoiceForm extends React.Component {
methodName1() {
}
methodName2 = () => {
};
}
例子2:类属性在外面
class Greeting extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
Greeting.propTypes = {
name: PropTypes.string
};
propTypes
在类之外。但为什么?我来自 python
,对于我来说,以下是更正确的
class Greeting extends React.Component {
static propTypes = {
name: PropTypes.string
}
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
最佳答案
What is the difference between the following two methods?
第一个是原型(prototype)方法 (this.__proto__.methodName1
),它没有绑定(bind)到 this
上下文,并且在 ES6 中有效。第二个是绑定(bind)到 this
上下文和 a part of a proposal 的实例方法 (this.methodName1
) .
propTypes is outside the class. But why?
因为 ES6 不支持类字段。由于该示例使用 JSX 并且应该以任何方式使用 Babel 构建,因此使用 ES.next 功能和 static propTypes = ...
字段是有意义的。
关于javascript - ES6 代码风格最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47623658/