首页 热点资讯 义务教育 高等教育 出国留学 考研考公
您的当前位置:首页正文

ReactNative之ES6与ES5区别

2024-12-20 来源:化拓教育网

解构复制

ES5
var React = require('react-native');
var View = React.View
ES6
var {View} = require('react-native')

导入模块

ES5
var other = require('./other');
ES6
import other from './other';
导出模块
ES5
var myCompnent = React.createClass({
   .....
});
module.exports = myCompnent;
ES6
var myCompnent = React.createClass({
    .....
});
exports default myCompnent;

ES 6语法采用export来代替module.exports

let和const

ES5
var a = 1;
ES6
let a = 1
a = 2
const PI = 3.1415
PI = 3 //error

ES 6 语法使用let声明变量,const声明只读变量

函数简写

ES5
render:function(){
    return xxx
}

ES6

render(){
    return xxx
}

箭头函数

ES5
var callback = function(v){

}.bind(this)

ES 5为了使函数与上下文保持一致,需要使用bind(this)

ES6
let callback =() = >{

}

ES 6使用箭头函数实现上下文自动绑定

字符串插值

ES5
var s1 = "React"
var s2 = s1 + " Native"
ES6
let s1 = "React"
let s2 = "${s1} Native"

Promise 异步

ES5
try{
this.doAsyncOperation(params,this.onSuccessCallBack,this.onErrorCallBack);
}catch(e){
}
ES6
this.doAsyncOperation(param).then((param) => {
}).catch((e)=>{
})
组件的属性类型和默认属性
ES5
var Video = React.createClass({
     getDefaultProps: function() { 
          return { 
            autoPlay: false, 
            maxLoops: 10, 
          };
     }, 
    propTypes: {
         autoPlay: React.PropTypes.bool.isRequired,
         maxLoops: React.PropTypes.number.isRequired,
         posterFrameSrc: React.PropTypes.string.isRequired,
         videoSrc: React.PropTypes.string.isRequired, 
     }, 
    render: function() { 
         return ( <View /> );
     },
});
ES6
class Video extends  {
      static defaultProps = { 
            autoPlay: false, 
            maxLoops: 10, 
        }
      static propTypes = { 
            autoPlay: React.PropTypes.bool.isRequired, 
            maxLoops: React.PropTypes.number.isRequired,
            posterFrameSrc: React.PropTypes.string.isRequired,
            videoSrc: React.PropTypes.string.isRequired, 
        }
      render() { 
            return ( 
                <View /> 
             );
        }
}

初始化STATE

ES5
var Video = React.createClass({ 
      getInitialState: function() {
             return { 
                    loopsRemaining: this.props.maxLoops,
               };
       },
})
ES6
class Video extends  { 
        constructor(props){ 
            super(props); 
            this.state = {
                   loopsRemaining: this.props.maxLoops, 
              }; 
        }
}
显示全文