React-理解高阶组件

高阶组件:定义一个函数,传入一个组件,返回另外一个组件,另外一个组件包裹了传入的组件。

分类:属性代理高阶组件,反向继承高阶组件。

作用:代码复用,渲染节时。

高阶函数例子:

function hello(){
    console.log('hello imooc I love React')
}

function WrapperHello(fn){
    return function(){
        console.log('before say hello')
        fn()
        console.log('after say hello')
    }
}
hello = WrapperHello(hello)
hello()

高阶组件例子:

//属性代理
function WrapperHello(Comp){
    class WrapComp extends React.Component{
        render(){
            return (<div>
                <p>这是HOC高阶组件特有的元素</p>
                <Comp name='text' {...this.props}></Comp>
            </div>)
        }
    }
    return WrapComp
}
WrapperHello(
  class Hello extends React.Component{
      render(){
          return <h2>hello imooc I love React&Rdux</h2>
      }
  }
)
//反向继承
function WrapperHello(Comp){
    class WrapComp extends Comp{
            componentDidMount(){
                console.log('高阶组件新增的生命周期,加载完成')
            }
            render(){
                return <Comp></Comp>
            }
    }
    return WrapComp
}
WrapperHello(
  class Hello extends React.Component{
      render(){
          return <h2>hello imooc I love React&Rdux</h2>
      }
  }
)

猜你喜欢

转载自www.cnblogs.com/superlizhao/p/9592694.html