Advanced components of React manuscript

Keywords: Javascript React

Higher-Order Components

  • HOC is not a standard API for React.
  • HOC is a function.
  • HOC returns a Component.

Example:

const EnhancedComponent = higherOrderComponent(WrappedComponent);

Usage scenarios

code reuse

Similar to mixin before React 0.15.

When multiple components use the same code or the same method, HOC can be used.

Example:

import React, { PureComponent } from 'react';

const Common = (WrapComponent) => {
  return (
    <div>
      <h1>Title</h1>
      <WrapComponent />
    </div>
  );
};

const Header = () => <div>Header</div>;
const Footer = () => <div>Footer</div>;

export default class extends PureComponent {
  render() {
    return (
      <div>
        <div>
          <p>Header Component</p>
          {Common(Header)}
        </div>
        <hr />
        <div>
          <p>Footer Component</p>
          {Common(Footer)}
        </div>
      </div>
    );
  }
}

Online example

Abstract state and change props

It can be abstracted through the component public state wrapped by WrappedComponent.

You can pass props for modification, addition, etc. through the wrapped component

Example:

const HOComp = (WrappedComponent) => {
  return class extends React.Component {
    constructor(props) {
      super(props);
      this.state = {name: ''};
    }

    componentDidMount() {
      this.setState({name: WrappedComponent.displayName || WrappedComponent.name || 'Component';});
    }

    return <WrappedComponent name={this.state.name} {...this.props}/>
  }
} 

Sham hijacking

The conditions are clear. Return the configuration content according to props or state conditions.

Example:

const HOComp = (WrappedComponent) => {
  return class Enhancer extends WrappedComponent {
    render() {
      if (this.props.loggedIn) {
        return super.render()
      } else {
        return null
      }
    }
  }
}

Reverse inheritance

The returned higher-order component class (Enhancer) inherits the WrappedComponent.

Example:

const EnchanceComponent = (WrappedCompopnent) => {
  return class extends WrappedCompopnent {
    constructor(props) {
      super(props);
      this.state = { error: '' };
    }
    componentDidMount() {
      /*do something*/
      super.componentDidMount();
    }
    render() {
      if (this.state.error) {
        return <div>{this.state.error}</div>;
      } else {
        return super.render();
      }
    }
  }
};

Online example

Posted by Threepwood on Fri, 06 Dec 2019 11:48:00 -0800