【高階組件和函數式編程】
function hello() { console.log('hello jason'); } function WrapperHello(fn) { return function() { console.log('before say hello'); fn(); console.log('after say hello'); } } // hello 這時候等於 WrapperHello函數中返回的 匿名函數 // 在設計模式中這種操作叫做 裝飾器模式 // 高階組件也是這種操作--把一個組件傳入,再返回一個新的組件 hello = WrapperHello(hello) hello()
【react中的高階組件】--HOC 組件就是一個函數
存在兩種高階組件:
1.屬性代理---主要進行組件的復用
2.反向集成---主要進行渲染的劫持
屬性代理的典型例子:
class Hello extends React.Component { render() { return <h4>hello Jason</h4> } } function WrapperHello(Comp) { class WrapComp extends React.Component { render() { return ( <div> <p>這是react高階組件特有的元素</p> <Comp {...this.props}></Comp> </div> ) } } return WrapComp; } Hello = WrapperHello(Hello)
還可以寫成裝飾器的模式,裝飾器就是一個典型的屬性代理高階組件
function WrapperHello(Comp) { class WrapComp extends React.Component { render() { return ( <div> <p>這是react高階組件特有的元素</p> <Comp {...this.props}></Comp> </div> ) } } return WrapComp; } @WrapperHello class Hello extends React.Component { render() { return <h4>hello Jason</h4> } }
反向集成: 組件和包裝組件之間的關系是繼承關系而不是代理的方式,可以修改原組件的生命周期,渲染流程和業務邏輯
function WrapperHello(Comp) { class WrapComp extends Comp { componentDidMount() { console.log('反向代理高階組件新增的生命周期,加載完成') } render() { return <Comp {...this.props}></Comp> } } return WrapComp; } @WrapperHello class Hello extends React.Component { componentDidMount() { console.log('組件加載完成') } render() { return <h4>hello Jason</h4> } }
控制台輸出:
組件加載完成
反向代理高階組件新增的生命周期,加載完成
希望對需要理解react高階組件的人給予幫助~
