国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

React 高階組件入門介紹

2024-05-06 16:41:55
字體:
來源:轉載
供稿:網友

高階組件的定義

HoC 不屬于 React 的 API,它是一種實現模式,本質上是一個函數,接受一個或多個 React 組件作為參數,返回一個全新的 React 組件,而不是改造現有的組件,這樣的組件被稱為高階組件。開發過程中,有的功能需要在多個組件類復用時,這時可以創建一個 Hoc。

基本用法

包裹方式

const HoC = (WrappendComponent) => { const WrappingComponent = (props) => (  <div className="container">   <WrappendComponent {...props} />  </div> ); return WrappingComponent;};

上述代碼中,接受 WrappendComponent 作為參數,此參數就是將要被 HoC 包裝的普通組件,在 render 中包裹一個 div,賦予它 className 屬性,最終產生的 WrappingComponent 和 傳入的 WrappendComponent 是兩個完全不同的組件。

在 WrappingComponent 中,可以讀取、添加、編輯、刪除傳給 WrappendComponent 的 props,也可以用其它元素包裹 WrappendComponent,用來實現封裝樣式、添加布局或其它操作。

組合方式

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 傳遞的參數可以為多個,傳遞多個組件定制新組件的行為,例如用戶登錄狀態下顯示主頁面,未登錄顯示登錄界面;在渲染列表時,傳入 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,共享父級的函數和屬性??梢允褂?super.render() 或者 super.componentWillUpdate() 調用父級的生命周期函數,但是這樣會讓兩個組件耦合在一起,降低組件的復用性。

React 中對組件的封裝是按照最小可用單元的思想來進行封裝的,理想情況下,一個組件只做一件事情,符合 OOP 中的單一職責原則。如果需要對組件的功能增強,通過組合的方式或者添加代碼的方式對組件進行增強,而不是修改原有的代碼。

注意事項

不要在 render 函數中使用高階組件

render() { // 每一次render函數調用都會創建一個新的EnhancedComponent實例 // EnhancedComponent1 !== EnhancedComponent2 const EnhancedComponent = enhance(MyComponent); // 每一次都會使子對象樹完全被卸載或移除 return <EnhancedComponent />;}

React 中的 diff 算法會比較新舊子對象樹,確定是否更新現有的子對象樹或丟掉現有的子樹并重新掛載。

必須將靜態方法做拷貝

// 定義靜態方法WrappedComponent.staticMethod = function() {/*...*/}// 使用高階組件const EnhancedComponent = enhance(WrappedComponent);// 增強型組件沒有靜態方法typeof EnhancedComponent.staticMethod === 'undefined' // true

Refs屬性不能傳遞

HoC中指定的 ref,并不會傳遞到子組件,需要通過回調函數使用 props 傳遞。

參考鏈接

高階組件

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 峡江县| 泾阳县| 呼图壁县| 黄梅县| 昌邑市| 镇平县| 和平区| 云和县| 维西| 浙江省| 平舆县| 成都市| 江口县| 双流县| 定陶县| 仪陇县| 宜黄县| 哈巴河县| 新邵县| 昌图县| 罗源县| 德昌县| 台东县| 绍兴市| 青岛市| 江达县| 张掖市| 榆社县| 丽水市| 台安县| 营口市| 科尔| 新源县| 临潭县| 阿拉善右旗| 大同县| 万载县| 桓台县| 凤凰县| 禹州市| 宁阳县|