【问题标题】:ES6 code styles best practicesES6 代码风格最佳实践
【发布时间】:2018-05-17 08:17:44
【问题描述】:

最近我开始学习 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>
    );
  }
}

【问题讨论】:

  • 在你的两个例子中,只有第一个 case 实际上是有效的 ES6 JavaScript,因为你不能直接在 class { ... } 中分配属性(无论它们是否是方法)。
  • 这是一个关于类属性提案的问题(因为它只是一个提案,所以无法回答)

标签: javascript ecmascript-6 ecmascript-5


【解决方案1】:

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

 methodName1() {   }

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

因此,如果您尝试访问像 this.setState 这样的 React 类属性/函数,您将收到错误消息(如果您没有在任何地方为 methodName1 使用绑定,例如:

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

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

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

 methodName2 = () => {
    };

箭头函数没有自己的 this 、参数、super 或 新目标。因此,此函数中的 this 关键字将引用 React 类 (React.Component) 的上下文,如 Here 所述

关于你的第二个问题

类外属性

我相信它使用 JSX ,并且 JSX 得到 Babel 的支持,并且 ES6 几乎肯定不会涵盖定义类变量的语法。您可以阅读更多内容Here

【讨论】:

    【解决方案2】:

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

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

    propTypes 在类之外。但为什么呢?

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

    【讨论】:

      猜你喜欢
      • 2012-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多