React 高階組件入門介紹
高階組件的定義
HoC 不屬于 React 的 API,它是一種實現(xiàn)模式,本質(zhì)上是一個函數(shù),接受一個或多個 React 組件作為參數(shù),返回一個全新的 React 組件,而不是改造現(xiàn)有的組件,這樣的組件被稱為高階組件。開發(fā)過程中,有的功能需要在多個組件類復(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() 調(diào)用父級的生命周期函數(shù),但是這樣會讓兩個組件耦合在一起,降低組件的復(fù)用性。
React 中對組件的封裝是按照最小可用單元的思想來進行封裝的,理想情況下,一個組件只做一件事情,符合 OOP 中的單一職責(zé)原則。如果需要對組件的功能增強,通過組合的方式或者添加代碼的方式對組件進行增強,而不是修改原有的代碼。
注意事項
不要在 render 函數(shù)中使用高階組件
render() {
// 每一次render函數(shù)調(diào)用都會創(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,并不會傳遞到子組件,需要通過回調(diào)函數(shù)使用 props 傳遞。
參考鏈接
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
react項目中使用react-dnd實現(xiàn)列表的拖拽排序功能
這篇文章主要介紹了react項目中使用react-dnd實現(xiàn)列表的拖拽排序,本文結(jié)合實例代碼講解react-dnd是如何實現(xiàn),代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-02-02
詳解如何用webpack4從零開始構(gòu)建react開發(fā)環(huán)境
這篇文章主要介紹了詳解如何用webpack4從零開始構(gòu)建react開發(fā)環(huán)境,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
React使用React.lazy和Suspense實現(xiàn)組件懶加載
React 提供了 React.lazy 和 Suspense 這兩個好東西,能讓我們實現(xiàn)組件的懶加載,下面就跟隨小編一起來了解一下如何使用它們實現(xiàn)懶加載的具體步驟吧2025-03-03

