ES6 代码风格最佳实践

ES6 code styles best practices

最近我开始学习 ReactJS,因此 - ES6。我对 ES5 很熟悉,但有些东西对我来说不是很清楚。

示例 1:方法语法

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

export class InvoiceForm extends React.Component {
    methodName1() {
    }

    methodName2 = () => {

    };
}

示例 2:Class 外部属性

class Greeting extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}

Greeting.propTypes = {
  name: PropTypes.string
};

propTypes在class之外。但为什么?我来自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?

第一个是原型方法(this.__proto__.methodName1),它没有绑定到this上下文,在ES6中有效。第二个是绑定到 this 上下文和 a part of a proposal.

的实例方法 (this.methodName1)

propTypes is outside the class. But why?

因为 class 字段在 ES6 中不受支持。由于该示例使用 JSX 并且应该以任何方式使用 Babel 构建,因此使用 ES.next 功能和 static propTypes = ... 字段是有意义的。

What is the difference between the following two methods?

 methodName1() {   }

上面是一个普通的函数,this这个函数中的关键字是指函数本身的上下文。

因此,如果您尝试像 this.setState 那样访问 React class Properties/functions,您将收到错误消息(如果您没有在任何地方为 methodName1 使用绑定,例如:

this.methodName1 = this.methondName1.bind(this) 很可能你想在构造方法中进行。

如果您想了解更多关于 this 绑定的信息,您可以查看 this Article

但是在第二种methodName2语法中,函数是使用箭头函数语法编写的。

 methodName2 = () => {
    };

An arrow function does not have its own this , arguments, super or new.target. Hence this keyword inside this function will refer to the context of the React class (React.Component) as described Here

关于你的第二个问题

Class properties outside

我相信因为它使用了 JSX,并且 JSX 被 Babel and ES6 will almost certainly not cover syntax for defining class variables. You can read more it

支持