React中es5与es6写法对比

1.引入与导出方式不同

  1. //ES5
  2. var React = require(“react”);
  1. //ES6
  2. import React, { Component, PropTypes } from ‘react

2.导入: ES5使用require导入,而ES6使用了import

  1. //ES5
  2. module.exports = Test;
  1. //ES6
  2. export default Test;

3.创建组件的方式不同

  1. //ES5
  2. var Test = React.createClass( {
  3.        ……….
  4. } );
  1. //ES6
  2. class Test extends Component {
  3.        ……….
  4. }

4.初始化组件属性的方式以及限制组件属性类型的方式不同

  1. //ES5
  2. var Test = React.createClass({
  3.       getDefaultProps: function() {
  4.              return {
  5.                    myPro: 10
  6.              };
  7.       },
  8.       propTypes: {
  9.              myPro: React.PropTypes.number. isRequired
  10.       }
  11. });
  12. //ES6
  13. class Test extends Component {
  14.        static defaultProps = {
  15.              myPro: 10
  16.        };
  17.        static propTypes = {
  18.              myPro: React.PropTypes.number. isRequired
  19.        };
  20. }

5.初始化方法不同

  1. //ES5
  2. getInitialState: function() {
  3.       ………..
  4.       return {
  5.            myState: 10
  6.       }
  7. }
  1. //ES6
  2. constructor(props){
  3.         super(props);
  4.         this.state = {
  5.             myState: 10
  6.         };
  7.     }

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注