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%A8 很多React/React Native的初学者都被ES6的问题迷惑:各路大神都建议我们直接学习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'
注意在React Native里,import直到0.12+才能正常运作。 导出单个类在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 (
{this.props.source} /> );
}
}
给组件定义方法从上面的例子里可以看到,给组件定义方法不再用 //ES5
var Photo = React.createClass({
componentWillMount: function(){
},render: function() {
return (
//ES6
class Photo extends React.Component {
componentWillMount() {
}
render() {
return (
定义组件的属性类型和默认属性
也有人这么写,虽然不推荐,但读到代码的时候你应当能明白它的意思: //ES6
class Video extends React.Component {
render() {
return (
View /> );
}
}
Video.defaultProps = {
autoPlay: false,};
Video.propTypes = {
autoPlay: React.PropTypes.bool.isRequired,};
注意:对React开发者而言,static成员在IE10及之前版本不能被继承,而在IE11和其它浏览器上可以,这有时候会带来一些问题。React Native开发者可以不用担心这个问题。 初始化STATEES5下情况类似, //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> )
},255); -webkit-text-stroke-width: 0px;">在ES5下,React.createClass会把所有的方法都bind一遍,这样可以提交到任意的地方作为回调函数,而this不会变化。但官方现在逐步认为这反而是不标准、不易理解的。
|