React-Native, ES5和ES6写法的区别总结

  • 引入模块的不同
//es5:
var React = require('react')
//es6(解构)
import React,{Component} from 'react'
  • 组件声明不同
//es5
//使用createClass,传入一个对象,所以内部要使用逗号
//需要显式定义getDefaultProps和getInitialState方法,在getInitialState方法里,需要返回一个对象
var MyModule = React.createClass({
//es5里必须写成:function(){}这种形式
  getDefaultProps:function(){
    times:0
  },

  getInitialState:function(){
    return {
      times : this.props.times
  }
},

render:function(){
    return(
      ***
    )
  }
})

//es6-更简洁,不需要逗号

class MyModule extends Component{
//不再需要显式定义getDefaultProps和getInitialState方法,在构造器内部干这两个事情
    constructor(props) {
      super(props);
      this.state = {times: this.props.times};
  }
//es6里的方法可以这样间歇
  render(){
    return(
        ***
        )
}

}

  • this的指向
//es5里this就指向这个组件本身
onPress={this.hintHandler}
//es6里必须要bind
onPress={this.hintHandler.bind(this)}

你可能感兴趣的:(React-Native, ES5和ES6写法的区别总结)