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)}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容