zva*_*dym 6 javascript ecmascript-5 ecmascript-6
最近我开始学习ReactJS,因此 - ES6.我对ES5非常熟悉,但有些事情对我来说并不是那么清楚.
示例1:方法语法
以下两种方法有什么区别?
export class InvoiceForm extends React.Component {
methodName1() {
}
methodName2 = () => {
};
}
Run Code Online (Sandbox Code Playgroud)
示例2:外部的类属性
class Greeting extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
Greeting.propTypes = {
name: PropTypes.string
};
Run Code Online (Sandbox Code Playgroud)
propTypes在课外.但为什么?我来自python和我一样,以下更正确
class Greeting extends React.Component {
static propTypes = {
name: PropTypes.string
}
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
Run Code Online (Sandbox Code Playgroud)
下面两种方法有什么区别?
methodName1() { }
Run Code Online (Sandbox Code Playgroud)
上面是一个普通函数,this该函数中的关键字指的是函数本身的上下文。
因此,如果您尝试访问 React 类属性/函数,this.setState您将收到错误(如果您没有在任何地方使用绑定)methodName1:
this.methodName1 = this.methondName1.bind(this)首先,您想在构造函数方法中执行此操作。
如果你想了解更多关于this绑定的知识可以看这篇文章
然而,在第二种methodName2语法中,函数是使用箭头函数语法编写的。
methodName2 = () => {
};
Run Code Online (Sandbox Code Playgroud)
箭头函数没有自己的 this 、arguments、super 或 new.target。因此,该函数内的 this 关键字将引用 React 类 (React.Component) 的上下文,如此处所述
关于你的第二个问题
外部类属性
我相信,由于它使用 JSX ,并且Babel支持 JSX ,并且 ES6 几乎肯定不会涵盖定义类变量的语法。您可以在这里阅读更多内容
| 归档时间: |
|
| 查看次数: |
1145 次 |
| 最近记录: |