High order component

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

Video Tutorial Address

  1. We define a function withLee that takes a component and returns that component
//import React, {Component, ComponentType} from "react"; Don't forget to import dependencies

function withLee<T> (Wrap: ComponentType<T>) :ComponentType<T> {
    return class extends Component<T> {
        render() {
            return <Wrap {. this.props} / >; }}}Copy the code
  1. Define a component and regenerate a new component using higher-order components

    interfaceIProps { name? :string
    }
    
    class Lee extends Component<IProps> {
        render() {
            return (
                <>
                    {this.props.name}
                </>)}}export default withLee<IProps>(Lee)
    Copy the code
  2. Using the component

    import React from 'react';
    import Lee from "./withLee";
    
    function App() {
        return (
            <>
                <Lee name='lee'/>
            </>
        );
    }
    
    export default App;
    
    Copy the code