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>
 } } )
相關文章
相關標籤/搜索