ReactNative学习笔记十三之ES6语法介绍

1,626 阅读2分钟

ES6 指的是ECMAScript 6.0,是JavaScrip的最新标准。为什么突然想到要介绍这个呢?之前我刚开始学习RN的时候还是没有ES6的,后来隔了一年多的时间,真正开始用ReactNative的时候,发现,语法变了,其实并不是语法变了,只是加入了一些新特性。有时候我们在github上看工程的时候,还会遇到ES5的语法,很多新开发者,有点一头雾水了,所以我在这里介绍一下ES6,并与ES5做个对比。

关于ReactNative交流群,这里要说一句,群二维码一周过期,有时候会忘了更新时间,需要的朋友可以留言告诉我,这次的二维码已更新


解构复制

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 React.Component {
    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 React.Component {
    constructor(props){
        super(props);
        this.state = {
            loopsRemaining: this.props.maxLoops,
        };
    }
}

总结

总的来说,ES 6相对于ES 5给开发者带来了更多的方便,使用起来也更加简单。上面记录了常用的一些差别,如果有兴趣了解更多关于ES6 的朋友,可以参考这一篇文章(es6.ruanyifeng.com/)。


之前文章合集:
Android文章合集
iOS文章合集
ReactNative文章合集
如果你也做ReactNative开发,并对ReactNative感兴趣,欢迎关注我的公众号,加入我们的讨论群: