52 RN note 10 differences between custom components in ES5 and ES6

1, General writing method of ES6 custom component

//1. Import resources
import React, { Component } from 'react';
import { Text, View } from 'react-native';
 
//2. Custom components
class Greeting extends Component {
  render() {
    return (
        <Text>Hello {this.props.name}!</Text>
    );
  }
}
 
//3. Import components and export
export default class LotsOfGreetings extends Component {
  render() {
    return (
      <View style={{flex:1,alignItems: 'center',justifyContent: "center"}}>
        <Greeting name='Rexxar' />
        <Greeting name='Jaina' />
        <Greeting name='Valeera' />
        {/* <Greeting name={true} /> */}
      </View>
    );
  }
}

2, Differences in importing resources

// ES5: use require
var React = require("react-native");
var {
     Image,
     Text,
     ProTypes
} = React; 
 

// ES6: use import
import React, {
   Image,
   Text,
   ProTypes
} from 'react-native';

3, Differences in component references

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

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

4, Defining the differences between components

// ES5: using createClass
var Phono = React.createClass({
    render:function(){
       return (
       <Image source = {this.props.source}/>
    );
  },
});
 
// ES6: using extends component
class Photo extends React.Component {
  render(){
      return (
      <Image source = {this.props.source}/>
     );
}

5, Differences in the way components are defined

// ES5
var Photo = React.createClass({
     componentWillMount:function(){
     
     },
     render:function(){
         return(
             <Image source = {this.props.source}/>
          );
      },
});
 
 
// ES6: omit function, use semicolon at the end of method instead of comma
class Photo extends React.Component {
   componentWillMount(){
}
  render(){
     reurn (
     <Image source = {this.props.source}/>
   );
}
}

6, Differences between component output class and external use

// ES5: through module.experts
var Mycomponent = React.createClass({
  .....
});
module.exports = MyComponent;
 
// ES6, usually use export default to achieve the same function
export default class MyComponent extends React.Component{
 ...

7, Difference between custom component property type and default property

//ES5: property type and default property are implemented by propTypes member and getDefaultProps method respectively
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 members can be used uniformly
class Video extends React.Component {
    static defaultProps = {
        autoPlay: false,
        maxLoops: 10,
    };  // Notice the semicolon here
    static propTypes = {
        autoPlay: React.PropTypes.bool.isRequired,
        maxLoops: React.PropTypes.number.isRequired,
        posterFrameSrc: React.PropTypes.string.isRequired,
        videoSrc: React.PropTypes.string.isRequired,
    };  // Notice the semicolon here
    render() {
        return (
            <View />
        );
    } // Notice that there's no semicolon or comma
}

8, Differences in initializing state

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

//ES6: writing method 1
class Video extends React.Component {
    state = {
        loopsRemaining: this.props.maxLoops,
    }
}
 
 
//ES6: write method 2: it is recommended to initialize in the constructor more easily (so you can also do some calculations as needed):
class Video extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            loopsRemaining: this.props.maxLoops,
        };
    }
}

9, The difference between using methods as callbacks

//ES5: React.createClass will bind all methods once,
        //This can be submitted to any place as a callback function, and this will not change
var PostInfo = React.createClass({
    handleOptionsButtonClick: function(e) {
        this.setState({showOptionsModal: true});
    },
    render: function(){
        return (
            <TouchableHighlight onPress={this.handleOptionsButtonClick}>
                <Text>{this.props.label}</Text>
            </TouchableHighlight>
        )
    },
});

//ES6: bind this reference through bind, or use arrow function (it will bind this reference of current scope) to call
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>
        )
    },
}

10, Add a new method to the class

//ES5: use mixin to add some new methods to our class, such as PureRenderMixin
var PureRenderMixin = require('react-addons-pure-render-mixin');
React.createClass({
  mixins: [PureRenderMixin],
 
  render: function() {
    return <div className={this.props.className}>foo</div>;
  }
});

//ES6: use an "enhanced function" to add some methods to a class and return a new class
//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

 

Tags: React

Posted on Mon, 06 Jan 2020 01:20:44 -0800 by Jason_London