Some differences between ES6 and ES5 in React.js

Keywords: React Attribute

1. Modules Introduction and Output
ES5 uses the CommonJS standard and generally uses require() to introduce modules:

var React = require('react');
var MyComponent = require('./MyComponent');

ES5 output module:

module.exports = MyComponent;

ES6 + import grammar introduction module:

import React from 'react';
import MyComponent from './MyComponent';

ES6 input module:

export default class MyComponent extends React.Component{

}

2. Classes, Method of Building Component
Use of React.createClass() in ES5

var Photo = React.createClass({
        render: function(){
            return (
                <div>
                    <images alt={this.props.description} src={this.props.src} />
                </div>
            )
        }
    });
ReactDOM.render(<Photo />, document.getElementById('root'));

Usage of es6 + class

class Photo extends React.Component{
        render(){
            return (
                <div>
                    <images alt={this.props.description} src={this.props.src} />
                </div>
            )
        }
    };
ReactDOM.render(<Photo />, document.getElementById('root'));

In ES5, we will define the component WillMount life cycle that we want to execute before render, and perform tasks only once.

var Photo = React.createClass({
        componentWillMount: function(){}
    })

ES6 + is defined in the constructor

class Photo extends React.Component{
        constructor(props){
            super(props);
            // Actions originally operated on component WillMount can be placed here
        }
    }

3. Method Method Method Definition
ES5 defines method grammar:

var Photo = React.createClass({
        handleClick: function(e){},
        render: function(){}
    });

ES6 can omit function s and commas (','):

class Photo extends React.Component{
        handleClick(e){}
        render(){}
    }

4. Property property initialization
ES5 grammar uses propTypes and getDefaultProps to define the default values and types of properties (props):

var Todo = React.createClass({
        getDefaultProps: function(){
            return {
                checked: false,
                maxLength: 10,
            };
        },
        propTypes: {
            checked: React.PropTypes.bool.isRequired,
            maxLengh: React.PropTypes.number.isRequired
        }, 
        render: function(){
            return ();
        }
    })

ES6 grammar, using static properties in class to define:

class Todo extends React.Component{
        static defaultProps = {
            checked: false,
            maxLength: 10,
        };
        static propTypes = {
            checked: React.PropTypes.bool.isRequired,
            maxLengh: React.PropTypes.number.isRequired
        };
        render(){
            return ();
        }
    }

Another way to write ES6:

   class Todo extends React.Component{
        render() {
            return(
                <View />
            )
        }
    };

    Todo.defaultProps = {
        checked: false,
        maxLength: 10,
    };

    Todo.propTypes = {
        checked: React.PropTypes.bool.isRequired,
        maxLengh: React.PropTypes.number.isRequired
    };

5. State status
ES5 grammar uses getInitialState to initialize state:

var Todo = React.createClass({
        getInitialState: function(){
            return {
                maxLength: this.props.maxLength
            }
        }
    })

There are two ways to initialize state in ES6 +, one is as follows:

class Todo extends React.Component{
        state = {
            maxLength: this.props.maxLength,
        }
    }

The other is written in the constructor.

class Todo extends React.Component{
        constructor(props){
            super(props);
            this.state = {
                maxLength: this.props.maxLength,
            }
        }
    }

6. Arrow functions arrow function
ES5 grammar, under React.createClass(), presupposes to help you bind this method, you do not have to bind it yourself:

var TodoBtn = React.createClass({
        handleButtonClick: function(e) {
            // This this refers to an instance of component, not a button.
            this.setState({showOptionsModal: true});
        },
        render: function(){
            return (
                <div>
                    <Button onClick={this.handleButtonClick}>{this.props.label}</Button>
                </div>
            )
        },
    });

ES6 + recommends binding this with bind or using Arrow functions (which bind this context of the current scope):

class TodoBtn extends React.Component{
        handleButtonClick(e){
            // Confirm that binding this refers to component instance
            this.setState({toggle: true});
        }
        render(){
            // You can use this.handleButtonClick.bind(this) manually or Arrow functions () => {} here.
            return (
                <div>
                    <Button onClick={this.handleButtonClick.bind(this)} onClick={(e)=> {this.handleButtonClick(e)} }>{this.props.label}</Button>
                </div>
            )
        },
    };

Whether it's bind or Arrow functions, each execution of the return refers to a new function. If you need to call the function again, save it first:

class TodoBtn extends React.Component{
        constructor(props){
            super(props);
            this.handleButtonClick = this.handleButtonClick.bind(this);
        }
        componentWillMount(){
            Btn.addEventListener('click', this.handleButtonClick);
        }
        componentDidmount(){
            Btn.removeEventListener('click', this.handleButtonClick);
        }
    };

7. Dynamic attribute names and Template Strings
In ES5, we need to dynamically set the attribute name, which often requires several more lines of code to achieve our goal:

var Todo = React.createClass({
        onChange: function(inputName, e){
            var stateToSet = {};
            stateToSet[inputName + 'Value'] = e.tartet.value;
            this.setState(stateToSet);
        }
    })

ES6 + is relatively simple to write:

class Todo extends React.Component{
        onChange(inputName, e) {
            this.setState({
                [`${inputName}Value`]: e.target.value,
            })
        }
    }

Posted by always_confused on Sun, 26 May 2019 15:10:11 -0700