Talk about several ways to create React Component

createClass

We can use this method to define components without using ES6 syntax

var React = require('react');
var Greeting = React.createClass({
  propTypes: {
    name: React.PropTypes.string  // Attribute verification
  },

  getDefaultProps: function() {
    return {
      name: 'Mary'  // Default attribute value
    }
  },

  getInitialState: function() {
    return {count: this.props.initialCount}; // Initialize state
  },

  handleClick: function() {
    // User click event handler
  },

  render: function() {
    return <h1>Hello, {this.props.name}</h1>;
  },
});

module.exports = Greeting;

Note: in createClass, React binds this to all the functions in the attribute, that is, the handleClick above is actually equivalent to handleClick.bind(this).

component

ES6 has syntax level support for classes and inheritance, so the way to create components with ES6 is more elegant

import React from 'react';

class Greeting extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: this.props.initialCount };
    this.handleClick = this.handleClick.bind(this);
  }

  //static defaultProps = {
  //  name: 'Mary' / / another way to define defaultprops 
  //}

  //static propTypes = {
  //  name: React.PropTypes.string / / another method of property verification
  //}

  handleClick() {
    // Click event handler
  }

  render() {
    return <h1>hello, {this.props.name}</h1>
  }
}

Greeting.propTypes = {
  name: React.PropsTypes.string
};

Greeting.defaultProps = {
  name: 'Mary'
};

export default Greeting;

Note: Greeting inherits from React.Component; In the constructor, the constructor of the parent class is called through super(), the state is assigned through this.state in the constructor, and the props of the component is created on the class Greeting.

When creating a component in this way, React does not bind this to the internal function. Therefore, if you maintain the correct this in the callback function, you need to bind this to the function manually, such as the handleClick function above, which binds this in the constructor.

PureComponent

When the props or state of a component changes, React will compare the current props and state of the component with nextProps and nextState respectively. When changes are found, it will re render the current component and sub components, otherwise it will not be rendered. Sometimes, in order to avoid unnecessary re rendering of components, we can optimize performance by defining shouldComponentUpdate.

class CounterButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count:1};
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.color !== this.nextProps.color) {
      return true;
    } 
    if (this.state.count !== this.nextState.count) {
      return true;
    }
    return false;
  }

  render() {
    return (
      <button
        color={this.props.color}
        onClick={() => this.setState(state => ({count: state.count + 1}))}>
        Count: {this.state.count}
      </button>
    )
  }
}

export default CounterButton;

Note: shouldComponentUpdate determines whether it is necessary to re render components by judging whether props.color and state.count have changed. Of course, sometimes this simple judgment is redundant and boilerplate, so React provides PureComponent to automatically help us do this, so there is no need to write shouldComponentUpdate manually

class CounterButton extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {count: 1};
  }

  render() {
    return (
      <button
        color={this.props.color}
        onClick={() => this.setState(state => ({count: state.count + 1}))}>
        Count: {this.state.count}
      </button>
    );
  }
}

Note: in most cases, using PureComponent can simplify our code and improve performance, but the shouldcomponentupdate function automatically added by PureComponent only makes a shadow comparison between props and state. When props or state itself is a nested object or array, etc, Shallow comparison can not get the expected results, which will lead to changes in the actual props and state, but the components are not updated.

You can consider using Immutable.js to create immutable objects, which can simplify object comparison and improve performance.

Stateless Functional Component

The above methods of creating components are used to create complex components including state and user interaction. When the component itself is only used for display and all data is passed in through props, we can use Stateless Functional Component to quickly create components.

import React from 'react';

const Button = ({ day, increment }) => {
  return (
    <div>
      <button onClick={increment}>Today id {day}</button>
    </div>
  );
}

Button.propsTypes = {
  day: propTypes.string.isRequired,
  increment: propTypes.func.isRequired,
}

export default Button;

Note: this Component does not have its own state. The same props input will inevitably obtain the same Component display. Because you don't need to care about some life cycle functions and rendering hooks of components, it's more concise not to inherit from components.



Author: the star_ fcaf
Link: https://www.jianshu.com/p/4119c5c52143
Source: Jianshu
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, and for non-commercial reprint, please indicate the source.

Keywords: React

Added by jokeruk on Fri, 26 Nov 2021 00:55:07 +0200