当前位置: 移动技术网 > IT编程>开发语言>JavaScript > React中ES5与ES6写法的区别总结

React中ES5与ES6写法的区别总结

2018年05月20日  | 移动技术网IT编程  | 我要评论

前言

相信很多react的初学者都被es6的问题迷惑:各路大神都建议我们直接学习es6的语法(class foo extends react.component),然而网上搜到的很多教程和例子都是es5版本的,所以很多人在学习的时候连照猫画虎都不知道怎么做。所以这篇文章就整理了一些es5和es6的写法对照表,希望大家以后读到es5的代码,也能通过对照,在es6下实现相同的功能。下面话不多说了,来看看详细的介绍吧。

模块

引用

在es5里,如果使用commonjs标准,引入react包基本通过require进行,代码类似这样:

//es5
var react = require("react");
var {
 component,
 proptypes
} = react; //引用react抽象组件

var reactnative = require("react-native");
var {
 image,
 text,
} = reactnative; //引用具体的react native组件

在es6里,import写法更为标准

//es6
import react, { 
 component,
 proptypes,
} from 'react';
import {
 image,
 text
} from 'react-native'

导出单个类

在es5里,要导出一个类给别的模块用,一般通过module.exports来导出

//es5
var mycomponent = react.createclass({
 ...
});
module.exports = mycomponent;

在es6里,通常用export default来实现相同的功能:

//es6
export default class mycomponent extends component{
 ...
}

引用的时候也类似:

//es5
var mycomponent = require('./mycomponent');

//es6
import mycomponent from './mycomponent';

注意:导入和导出的写法必须配套,不能混用!

定义组件

在es5里,通常通过react.createclass来定义一个组件类,像这样:

//es5
var photo = react.createclass({
 render: function() {
  return (
   <image source={this.props.source} />
  );
 },
});

在es6里,我们通过定义一个继承自react.component的class来定义一个组件类,像这样:

//es6
class photo extends react.component {
 render() {
  return (
   <image source={this.props.source} />
  );
 }
}

给组件定义方法

从上面的例子里可以看到,给组件定义方法不再用 名字: function()的写法,而是直接用名字(),在方法的最后也不能有逗号了。

//es5 
var photo = react.createclass({
 componentwillmount: function(){

 },
 render: function() {
  return (
   <image source={this.props.source} />
  );
 },
});
//es6
class photo extends react.component {
 componentwillmount() {

 }
 render() {
  return (
   <image source={this.props.source} />
  );
 }
}

定义组件的属性类型和默认属性

在es5里,属性类型和默认属性分别通过proptypes成员和getdefaultprops方法来实现

//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里,可以统一使用static成员来实现

//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 />
  );
 } // 注意这里既没有分号也没有逗号
}

也有人这么写,虽然不推荐,但读到代码的时候你应当能明白它的意思:

//es6
class video extends react.component {
 render() {
  return (
   <view />
  );
 }
}
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和其它浏览器上可以,这有时候会带来一些问题。react native开发者可以不用担心这个问题。

初始化state

es5下情况类似,

//es5 
var video = react.createclass({
 getinitialstate: function() {
  return {
   loopsremaining: this.props.maxloops,
  };
 },
})

es6下,有两种写法:

//es6
class video extends react.component {
 state = {
  loopsremaining: this.props.maxloops,
 }
}

不过我们推荐更易理解的在构造函数中初始化(这样你还可以根据需要做一些计算):

//es6
class video extends react.component {
 constructor(props){
  super(props);
  this.state = {
   loopsremaining: this.props.maxloops,
  };
 }
}

把方法作为回调提供

很多习惯于es6的用户反而不理解在es5下可以这么做:

//es5
var postinfo = react.createclass({
 handleoptionsbuttonclick: function(e) {
  // here, 'this' refers to the component instance.
  this.setstate({showoptionsmodal: true});
 },
 render: function(){
  return (
   <touchablehighlight onpress={this.handleoptionsbuttonclick}>
    <text>{this.props.label}</text>
   </touchablehighlight>
  )
 },
});

在es5下,react.createclass会把所有的方法都bind一遍,这样可以提交到任意的地方作为回调函数,而this不会变化。但官方现在逐步认为这反而是不标准、不易理解的。

在es6下,你需要通过bind来绑定this引用,或者使用箭头函数(它会绑定当前scope的this引用)来调用

//es6
class postinfo extends react.component
{
 handleoptionsbuttonclick(e){
  this.setstate({showoptionsmodal: true});
 }
 render(){
  return (
   <touchablehighlight 
    onpress={this.handleoptionsbuttonclick.bind(this)}
    onpress={e=>this.handleoptionsbuttonclick(e)}
    >
    <text>{this.props.label}</text>
   </touchablehighlight>
  )
 },
}

箭头函数实际上是在这里定义了一个临时的函数,箭头函数的箭头=>之前是一个空括号、单个的参数名、或用括号括起的多个参数名,而箭头之后可以是一个表达式(作为函数的返回值),或者是用花括号括起的函数体(需要自行通过return来返回值,否则返回的是undefined)。

// 箭头函数的例子
()=>1
v=>v+1
(a,b)=>a+b
()=>{
 alert("foo");
}
e=>{
 if (e == 0){
  return 0;
 }
 return 1000/e;
}

需要注意的是,不论是bind还是箭头函数,每次被执行都返回的是一个新的函数引用,因此如果你还需要函数的引用去做一些别的事情(譬如卸载监听器),那么你必须自己保存这个引用

// 错误的做法
class pausemenu extends react.component{
 componentwillmount(){
  appstateios.addeventlistener('change', this.onapppaused.bind(this));
 }
 componentdidunmount(){
  appstateios.removeeventlistener('change', this.onapppaused.bind(this));
 }
 onapppaused(event){
 }
}
// 正确的做法
class pausemenu extends react.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){
 }
}

从网上我们还学习到一种新的做法:

// 正确的做法
class pausemenu extends react.component{
 componentwillmount(){
  appstateios.addeventlistener('change', this.onapppaused);
 }
 componentdidunmount(){
  appstateios.removeeventlistener('change', this.onapppaused);
 }
 onapppaused = (event) => {
  //把方法直接作为一个arrow function的属性来定义,初始化的时候就绑定好了this指针
 }
}

mixins

在es5下,我们经常使用mixin来为我们的类添加一些新的方法,譬如purerendermixin

var purerendermixin = require('react-addons-pure-render-mixin');
react.createclass({
 mixins: [purerendermixin],

 render: function() {
  return <div classname={this.props.classname}>foo</div>;
 }
});

然而现在官方已经不再打算在es6里继续推行mixin,他们说:mixins are dead. long live composition

尽管如果要继续使用mixin,还是有一些第三方的方案可以用,譬如

不过官方推荐,对于库编写者而言,应当尽快放弃mixin的编写方式,上文中提到sebastian markbåge的一段代码推荐了一种新的编码方式:

//enhance.js
import { component } from "react";

export var enhance = composedcomponent => class extends component {
 constructor() {
  this.state = { data: null };
 }
 componentdidmount() {
  this.setstate({ data: 'hello' });
 }
 render() {
  return <composedcomponent {...this.props} data={this.state.data} />;
 }
};
//higherordercomponent.js
import { enhance } from "./enhance";

class mycomponent {
 render() {
  if (!this.data) return <div>waiting...</div>;
  return <div>{this.data}</div>;
 }
}

export default enhance(mycomponent); // enhanced component

用一个“增强函数”,来某个类增加一些方法,并且返回一个新类,这无疑能实现mixin所实现的大部分需求。

es6+带来的其它好处

解构&属性延展

结合使用es6+的解构和属性延展,我们给孩子传递一批属性更为方便了。这个例子把classname以外的所有属性传递给div标签:

class autoloadingpostsgrid extends react.component {
  render() {
    var {
      classname,
      ...others, // contains all properties of this.props except for classname
    } = this.props;
    return (
      <div classname={classname}>
        <postsgrid {...others} />
        <button onclick={this.handleloadmoreclick}>load more</button>
      </div>
    );
  }
}

下面这种写法,则是传递所有属性的同时,用覆盖新的classname值:

<div {...this.props} classname="override">
  …
</div>

这个例子则相反,如果属性中没有包含classname,则提供默认的值,而如果属性中已经包含了,则使用属性中的值

<div classname="base" {...this.props}>
  …
</div>

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网