最近我开始学习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>
);
}
}
答案 0 :(得分:2)
以下两种方法有什么区别?
第一个是原型方法(this.__proto__.methodName1
),它没有绑定到this
上下文并且在ES6中有效。第二个是实例方法(this.methodName1
),它绑定到this
上下文和a part of a proposal。
propTypes在类之外。但为什么呢?
因为ES6不支持类字段。由于该示例使用JSX并且应该以任何方式使用Babel构建,因此使用ES.next功能和static propTypes = ...
字段是有意义的。
答案 1 :(得分:1)
以下两种方法有什么区别?
methodName1() { }
以上是正常函数,此函数中的this
关键字是指函数本身的上下文。
因此,如果您尝试访问React类属性/函数(例如this.setState
),则会出现错误(如果您未在methodName1
的任何位置使用绑定,请执行以下操作:
this.methodName1 = this.methondName1.bind(this)
prefarbaly你想在构造函数方法中做到这一点。
如果您想了解有关this
绑定的更多信息,请参阅this Article
然而,在第二个methodName2
语法中,函数是使用箭头函数语法编写的。
methodName2 = () => {
};
箭头函数没有自己的this,arguments,super或 new.target。因此,此函数中的此关键字将引用 React类(React.Component)的上下文,如Here
所述
关于你的第二个问题
之外的类属性