javascript - ES6 代码风格最佳实践

标签 javascript ecmascript-6 ecmascript-5

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

最佳答案

What is the difference between the following two methods?

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

propTypes is outside the class. But why?

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

关于javascript - ES6 代码风格最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47623658/

相关文章:

javascript - 我怎样才能改变angularjs spinners的颜色

javascript - 使用 Javascript 制作比赛游戏

javascript - rollupjs - babelHelpers 对象未创建

Javascript 条件正则表达式 if-then-else

javascript - 基于字段对数组中的对象之一进行操作

javascript - .click() 仅在 iPad 中不起作用,在 backbone.js 应用程序内部

javascript - 我可以在 ZingChart 中通过单个 renderfunction 调用来渲染多个图表吗?

reactjs - 使用 Webpack 和 ES6 的 Fine Uploader

javascript - 为什么我的导入在 Chrome 67 的 EMCAScript 6 中不起作用?

javascript - 将语句转换为 ES5