Loadding..

React And React Native ES5 And ES6

React And React Native ES5 And ES6

REFERENCE

In ES5, if you use CommonJS standard, the introduction of React package through basic require, the code is similar to this:

//ES5
var React = require("react");
var {
    Component,
    PropTypes
} = React;  

var ReactNative = require("react-native");
var {
    Image,
    Text,
} = ReactNative; 

In ES6, the import wording is more standard

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

Note that in React Native, import will not work until 0.12+.

 

EXPORT A SINGLE CLASS

In ES5, to export a class to other modules, generally through module.exports to export

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

In ES6, export default is usually used to achieve the same function:

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

Quote time is similar:

//ES5
var MyComponent = require('./MyComponent');

//ES6
import MyComponent from './MyComponent';



Define a component

In ES5, it is common to define a component class via React.createClass, like so:

//ES5
var Photo = React.createClass({
    render: function() {
        return (
            <Image source={this.props.source} />
        );
    },
});

In ES6, we define a component class by defining a class that is inherited from React.Component, like so:

//ES6
class Photo extends React.Component {
    render() {
        return (
            <Image source={this.props.source} />
        );
    }
}


DEFINES A METHOD FOR THE COMPONENT

You can see from the above example, the method is no longer used to define the components of 名字: function()the wording, but the direct use 名字()in the final method can not have a comma.

//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} />
        );
    }
}



INITIALIZES STATE

ES5 under similar circumstances,

//ES5 
var Video = React.createClass({
    getInitialState: function() {
        return {
            loopsRemaining: this.props.maxLoops,
        };
    },
})

ES6, there are two kinds of writing:

//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,
        };
    }
}
Print
Image

enqtran

I'm enqtran - A coder and blogger :) [email protected]