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

首頁 > 編程 > JavaScript > 正文

React 高階組件入門介紹

2019-11-19 14:32:41
字體:
供稿:網(wǎng)友

高階組件的定義

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í)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 泸水县| 香港 | 同江市| 天津市| 云霄县| 忻城县| 朝阳县| 东光县| 营山县| 新乡市| 锡林浩特市| 嵊州市| 赤城县| 长宁县| 内黄县| 西充县| 平塘县| 溧阳市| 濮阳县| 凤冈县| 南川市| 石家庄市| 黔江区| 岳阳市| 新龙县| 昭觉县| 乳山市| 垣曲县| 宜春市| 福州市| 梅州市| 绵竹市| 娄烦县| 睢宁县| 乐至县| 昌图县| 柳河县| 兰溪市| 新巴尔虎右旗| 华蓥市| 鱼台县|