HOC: High-level component

A higher-order component is a function that takes a component as an argument and returns a new component.

  • Example: Obtain the value of mouse position X and y by moving the mouse.

1. Encapsulate a higher-order component:

// WrappedComponent is a component passed in as an argument
const withMouse = (WrappedComponent) = > {
    // Redefine a class component
    class withMouseComponent extends React.Component {
        constructor(props) {
            super(props)
            // The initial values of x and y are set to 0
            this.state = { x: 0.y: 0 }
        }
  
        handleMouseMove = (event) = > {
            // Reassign x and y with mouse movement
            this.setState({
                x: event.clientX,
                y: event.clientY
            })
        }
  
        render() {
            return (
                <div style={{ height: '500px'}}onMouseMove={this.handleMouseMove}>{/* 1. Pass through all props 2.<WrappedComponent {. this.props} mouse={this.state}/>
                </div>)}}// Returns the new component
    return withMouseComponent
}
Copy the code

2. Use components

// Create a function component App
const App = (props) = > {
    // Since the component encapsulated above passes through props, you can get properties on the component here
    const testProp = props.testProp
    const { x, y } = props.mouse // Receive mouse attributes
    return({/* Write a simple container that displays the mouse position */}
        <div style={{ height: '500px'}} ><h1>The mouse position is ({x}, {y})</h1>
            <p>{ testProp }</p>
        </div>
    )
}

// App is passed withMouse as an argument to the higher-order component
const HOCDemo = withMouse(App);

// render uses components
<HOCDemo testProp="Test passthrough properties" />
Copy the code