React中ES5与ES6写法的区别总结
前言
相信很多React的初学者都被ES6的问题迷惑:各路大神都建议我们直接学习ES6的语法(classFooextendsReact.Component),然而网上搜到的很多教程和例子都是ES5版本的,所以很多人在学习的时候连照猫画虎都不知道怎么做。所以这篇文章就整理了一些ES5和ES6的写法对照表,希望大家以后读到ES5的代码,也能通过对照,在ES6下实现相同的功能。下面话不多说了,来看看详细的介绍吧。
模块
引用
在ES5里,如果使用CommonJS标准,引入React包基本通过require进行,代码类似这样:
//ES5
varReact=require("react");
var{
Component,
PropTypes
}=React;//引用React抽象组件
varReactNative=require("react-native");
var{
Image,
Text,
}=ReactNative;//引用具体的ReactNative组件
在ES6里,import写法更为标准
//ES6
importReact,{
Component,
PropTypes,
}from'react';
import{
Image,
Text
}from'react-native'
导出单个类
在ES5里,要导出一个类给别的模块用,一般通过module.exports来导出
//ES5
varMyComponent=React.createClass({
...
});
module.exports=MyComponent;
在ES6里,通常用exportdefault来实现相同的功能:
//ES6
exportdefaultclassMyComponentextendsComponent{
...
}
引用的时候也类似:
//ES5
varMyComponent=require('./MyComponent');
//ES6
importMyComponentfrom'./MyComponent';
注意:导入和导出的写法必须配套,不能混用!
定义组件
在ES5里,通常通过React.createClass来定义一个组件类,像这样:
//ES5
varPhoto=React.createClass({
render:function(){
return(
);
},
});
在ES6里,我们通过定义一个继承自React.Component的class来定义一个组件类,像这样:
//ES6
classPhotoextendsReact.Component{
render(){
return(
);
}
}
给组件定义方法
从上面的例子里可以看到,给组件定义方法不再用名字:function()的写法,而是直接用名字(),在方法的最后也不能有逗号了。
//ES5
varPhoto=React.createClass({
componentWillMount:function(){
},
render:function(){
return(
);
},
});
//ES6
classPhotoextendsReact.Component{
componentWillMount(){
}
render(){
return(
);
}
}
定义组件的属性类型和默认属性
在ES5里,属性类型和默认属性分别通过propTypes成员和getDefaultProps方法来实现
//ES5
varVideo=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(
);
},
});
在ES6里,可以统一使用static成员来实现
//ES6
classVideoextendsReact.Component{
staticdefaultProps={
autoPlay:false,
maxLoops:10,
};//注意这里有分号
staticpropTypes={
autoPlay:React.PropTypes.bool.isRequired,
maxLoops:React.PropTypes.number.isRequired,
posterFrameSrc:React.PropTypes.string.isRequired,
videoSrc:React.PropTypes.string.isRequired,
};//注意这里有分号
render(){
return(
);
}//注意这里既没有分号也没有逗号
}
也有人这么写,虽然不推荐,但读到代码的时候你应当能明白它的意思:
//ES6
classVideoextendsReact.Component{
render(){
return(
);
}
}
Video.defaultProps={
autoPlay:false,
maxLoops:10,
};
Video.propTypes={
autoPlay:React.PropTypes.bool.isRequired,
maxLoops:React.PropTypes.number.isRequired,
posterFrameSrc:React.PropTypes.string.isRequired,
videoSrc:React.PropTypes.string.isRequired,
};
注意:对React开发者而言,static成员在IE10及之前版本不能被继承,而在IE11和其它浏览器上可以,这有时候会带来一些问题。ReactNative开发者可以不用担心这个问题。
初始化STATE
ES5下情况类似,
//ES5
varVideo=React.createClass({
getInitialState:function(){
return{
loopsRemaining:this.props.maxLoops,
};
},
})
ES6下,有两种写法:
//ES6
classVideoextendsReact.Component{
state={
loopsRemaining:this.props.maxLoops,
}
}
不过我们推荐更易理解的在构造函数中初始化(这样你还可以根据需要做一些计算):
//ES6
classVideoextendsReact.Component{
constructor(props){
super(props);
this.state={
loopsRemaining:this.props.maxLoops,
};
}
}
把方法作为回调提供
很多习惯于ES6的用户反而不理解在ES5下可以这么做:
//ES5
varPostInfo=React.createClass({
handleOptionsButtonClick:function(e){
//Here,'this'referstothecomponentinstance.
this.setState({showOptionsModal:true});
},
render:function(){
return(
{this.props.label}
)
},
});
在ES5下,React.createClass会把所有的方法都bind一遍,这样可以提交到任意的地方作为回调函数,而this不会变化。但官方现在逐步认为这反而是不标准、不易理解的。
在ES6下,你需要通过bind来绑定this引用,或者使用箭头函数(它会绑定当前scope的this引用)来调用
//ES6
classPostInfoextendsReact.Component
{
handleOptionsButtonClick(e){
this.setState({showOptionsModal:true});
}
render(){
return(
this.handleOptionsButtonClick(e)}
>
{this.props.label}
)
},
}
箭头函数实际上是在这里定义了一个临时的函数,箭头函数的箭头=>之前是一个空括号、单个的参数名、或用括号括起的多个参数名,而箭头之后可以是一个表达式(作为函数的返回值),或者是用花括号括起的函数体(需要自行通过return来返回值,否则返回的是undefined)。
//箭头函数的例子
()=>1
v=>v+1
(a,b)=>a+b
()=>{
alert("foo");
}
e=>{
if(e==0){
return0;
}
return1000/e;
}
需要注意的是,不论是bind还是箭头函数,每次被执行都返回的是一个新的函数引用,因此如果你还需要函数的引用去做一些别的事情(譬如卸载监听器),那么你必须自己保存这个引用
//错误的做法
classPauseMenuextendsReact.Component{
componentWillMount(){
AppStateIOS.addEventListener('change',this.onAppPaused.bind(this));
}
componentDidUnmount(){
AppStateIOS.removeEventListener('change',this.onAppPaused.bind(this));
}
onAppPaused(event){
}
}
//正确的做法
classPauseMenuextendsReact.Component{
constructor(props){
super(props);
this._onAppPaused=this.onAppPaused.bind(this);
}
componentWillMount(){
AppStateIOS.addEventListener('change',this._onAppPaused);
}
componentDidUnmount(){
AppStateIOS.removeEventListener('change',this._onAppPaused);
}
onAppPaused(event){
}
}
从网上我们还学习到一种新的做法:
//正确的做法
classPauseMenuextendsReact.Component{
componentWillMount(){
AppStateIOS.addEventListener('change',this.onAppPaused);
}
componentDidUnmount(){
AppStateIOS.removeEventListener('change',this.onAppPaused);
}
onAppPaused=(event)=>{
//把方法直接作为一个arrowfunction的属性来定义,初始化的时候就绑定好了this指针
}
}
Mixins
在ES5下,我们经常使用mixin来为我们的类添加一些新的方法,譬如PureRenderMixin
varPureRenderMixin=require('react-addons-pure-render-mixin');
React.createClass({
mixins:[PureRenderMixin],
render:function(){
returnfoo 然而现在官方已经不再打算在ES6里继续推行Mixin,他们说:MixinsAreDead.LongLiveComposition。
尽管如果要继续使用mixin,还是有一些第三方的方案可以用,譬如这个方案
不过官方推荐,对于库编写者而言,应当尽快放弃Mixin的编写方式,上文中提到SebastianMarkbåge的一段代码推荐了一种新的编码方式:
//Enhance.js
import{Component}from"React";
exportvarEnhance=ComposedComponent=>classextendsComponent{
constructor(){
this.state={data:null};
}
componentDidMount(){
this.setState({data:'Hello'});
}
render(){
return ;
}
};
//HigherOrderComponent.js
import{Enhance}from"./Enhance";
classMyComponent{
render(){
if(!this.data)returnWaiting...;
return{this.data};
}
}
exportdefaultEnhance(MyComponent);//Enhancedcomponent
用一个“增强函数”,来某个类增加一些方法,并且返回一个新类,这无疑能实现mixin所实现的大部分需求。
ES6+带来的其它好处
解构&属性延展
结合使用ES6+的解构和属性延展,我们给孩子传递一批属性更为方便了。这个例子把className以外的所有属性传递给div标签:
classAutoloadingPostsGridextendsReact.Component{
render(){
var{
className,
...others,//containsallpropertiesofthis.propsexceptforclassName
}=this.props;
return(
Loadmore
下面这种写法,则是传递所有属性的同时,用覆盖新的className值:
…
这个例子则相反,如果属性中没有包含className,则提供默认的值,而如果属性中已经包含了,则使用属性中的值
…