ES6代码样式最佳实践 [英] ES6 code styles best practices

查看:374
本文介绍了ES6代码样式最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我开始学习ReactJS,因此 - ES6。我对ES5非常熟悉,但有些事情对我来说并不是那么清楚。

Recently I've started to learn ReactJS and consequently - ES6. I'm quite familiar with ES5, but some things are not that clear for me.

示例1:方法语法

以下两种方法有什么区别?

What is the difference between the following two methods?

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 ,对我来说,以下更正确

propTypes is outside the class. But why? I came from python and as for me, the following is more correct

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?



 methodName1() {   }

以上是正常函数,此函数中的关键字是指函数本身的上下文。

above is a normal function and this keyword in this function refers to the context of the function itself.

因此,如果您尝试访问React类属性/函数,如这个。 setState 你会收到一个错误(如果你没有在 methodName1 的任何地方使用绑定,如:

So if you try to access React class Properties/functions like this.setState you will get an error (if you haven't used binding anywhere for methodName1 like :

this.methodName1 = this.methondName1.bind(this) prefarbaly你想在构造函数方法中做到这一点。

this.methodName1 = this.methondName1.bind(this) prefarbaly you want to do it inside constructor method.

如果您想了解更多关于绑定的信息,您可以看到这篇文章

If you want to learn more about this binding you can see this Article

然而在seco nd methodName2 语法,函数是使用箭头函数语法编写的。

However In the second methodName2 syntax, function is written using Arrow function syntax.

 methodName2 = () => {
    };




箭头函数没有自己的这个,参数,超级或者
new.target。因此,此函数中的此关键字将引用React类(React.Component)的
上下文,如这里

关于你的第二个问题


外面的类属性

Class properties outside

我相信它使用JSX和JSX受 Babel 支持,ES6几乎肯定不会涵盖定义类变量的语法。您可以阅读更多信息此处

I believe as it uses JSX , and JSX is supported by Babel and ES6 will almost certainly not cover syntax for defining class variables. You can read more it Here

这篇关于ES6代码样式最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆