React 高階組件入門介紹
高階組件的定義
HoC 不屬于 React 的 API,它是一種實現(xiàn)模式,本質上是一個函數(shù),接受一個或多個 React 組件作為參數(shù),返回一個全新的 React 組件,而不是改造現(xiàn)有的組件,這樣的組件被稱為高階組件。開發(fā)過程中,有的功能需要在多個組件類復用時,這時可以創(chuàng)建一個 Hoc。
基本用法
包裹方式
const HoC = (WrappendComponent) => { const WrappingComponent = (props) => ( <div className="container"> <WrappendComponent {...props} /> </div> ); return WrappingComponent; };
上述代碼中,接受 WrappendComponent 作為參數(shù),此參數(shù)就是將要被 HoC 包裝的普通組件,在 render 中包裹一個 div,賦予它 className 屬性,最終產(chǎn)生的 WrappingComponent 和 傳入的 WrappendComponent 是兩個完全不同的組件。
在 WrappingComponent 中,可以讀取、添加、編輯、刪除傳給 WrappendComponent 的 props,也可以用其它元素包裹 WrappendComponent,用來實現(xiàn)封裝樣式、添加布局或其它操作。
組合方式
const HoC = (WrappedComponent, LoginView) => { const WrappingComponent = () => { const {user} = this.props; if (user) { return <WrappedComponent {...this.props} /> } else { return <LoginView {...this.props} /> } }; return WrappingComponent; };
上述代碼中有兩個組件,WrappedComponent 和 LoginView,如果傳入的 props 中存在 user,則正常顯示的 WrappedComponent 組件,否則顯示 LoginView 組件,讓用戶去登錄。HoC 傳遞的參數(shù)可以為多個,傳遞多個組件定制新組件的行為,例如用戶登錄狀態(tài)下顯示主頁面,未登錄顯示登錄界面;在渲染列表時,傳入 List 和 Loading 組件,為新組件添加加載中的行為。
繼承方式
const HoC = (WrappendComponent) => { class WrappingComponent extends WrappendComponent { render() ( const {user, ...otherProps} = this.props; this.props = otherProps; return super.render(); } } return WrappingComponent; };
WrappingComponent 是一個新組件,它繼承自 WrappendComponent,共享父級的函數(shù)和屬性。可以使用 super.render() 或者 super.componentWillUpdate() 調用父級的生命周期函數(shù),但是這樣會讓兩個組件耦合在一起,降低組件的復用性。
React 中對組件的封裝是按照最小可用單元的思想來進行封裝的,理想情況下,一個組件只做一件事情,符合 OOP 中的單一職責原則。如果需要對組件的功能增強,通過組合的方式或者添加代碼的方式對組件進行增強,而不是修改原有的代碼。
注意事項
不要在 render 函數(shù)中使用高階組件
render() { // 每一次render函數(shù)調用都會創(chuàng)建一個新的EnhancedComponent實例 // EnhancedComponent1 !== EnhancedComponent2 const EnhancedComponent = enhance(MyComponent); // 每一次都會使子對象樹完全被卸載或移除 return <EnhancedComponent />; }
React 中的 diff 算法會比較新舊子對象樹,確定是否更新現(xiàn)有的子對象樹或丟掉現(xiàn)有的子樹并重新掛載。
必須將靜態(tài)方法做拷貝
// 定義靜態(tài)方法 WrappedComponent.staticMethod = function() {/*...*/} // 使用高階組件 const EnhancedComponent = enhance(WrappedComponent); // 增強型組件沒有靜態(tài)方法 typeof EnhancedComponent.staticMethod === 'undefined' // true
Refs屬性不能傳遞
HoC中指定的 ref,并不會傳遞到子組件,需要通過回調函數(shù)使用 props 傳遞。
參考鏈接
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
React Native開發(fā)封裝Toast與加載Loading組件示例
這篇文章主要介紹了React Native開發(fā)封裝Toast與加載Loading組件,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-09-09解決React報錯Encountered?two?children?with?the?same?key
這篇文章主要為大家介紹了React報錯Encountered?two?children?with?the?same?key解決方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12React關于antd table中select的設值更新問題
這篇文章主要介紹了React關于antd table中select的設值更新問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03react-router v4如何使用history控制路由跳轉詳解
這篇文章主要給大家介紹了關于react-router v4如何使用history控制路由跳轉的相關資料,文中通過示例代碼介紹的的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。2018-01-01