React-理解高阶组件

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

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

做用:代码复用,渲染节时。this

高阶函数例子:spa

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>
 } } )
相关文章
相关标签/搜索