React/React Native 的ES5 ES6写法对照表

转载: http://bbs.reactnative.cn/topic/15/react-react-native-%E7%9A%84es5-es6%E5%86%99%E6%B3%95%E5%AF%B9%E7%85%A7%E8%A1%A8javascript

英文版: https://babeljs.io/blog/2015/06/07/react-on-es6-plusjava

 

 

不少React/React Native的初学者都被ES6的问题迷惑:各路大神都建议咱们直接学习ES6的语法(class Foo extends React.Component),然而网上搜到的不少教程和例子都是ES5版本的,因此不少人在学习的时候连照猫画虎都不知道怎么作。今天在此整理了一些ES5和ES6的写法对照表,但愿你们之后读到ES5的代码,也能经过对照,在ES6下实现相同的功能。react


模块

引用

在ES5里,若是使用CommonJS标准,引入React包基本经过require进行,代码相似这样:git

//ES5 var React = require("react-native"); var { Image, Text, PropTypes } = React; //引用不一样的React Native组件 

在ES6里,import写法更为标准es6

//ES6 import React, { Image, Text, PropTypes } from 'react-native'; 

注意在React Native里,import直到0.12+才能正常运做。github

导出单个类

在ES5里,要导出一个类给别的模块用,通常经过module.exports来导出npm

//ES5 var MyComponent = React.createClass({ ... }); module.exports = MyComponent; 

在ES6里,一般用export default来实现相同的功能:react-native

//ES6 export default class MyComponent extends React.Component{ ... } 

引用的时候也相似:浏览器

//ES5 var MyComponent = require('./MyComponent.js'); //ES6 import MyComponent from './MyComponent.js'; 

定义组件

在ES5里,一般经过React.createClass来定义一个组件类,像这样:babel

//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>
相关文章
相关标签/搜索