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

首頁 > 語言 > JavaScript > 正文

React 高階組件入門介紹

2024-05-06 15:22:43
字體:
來源:轉載
供稿:網友

高階組件的定義

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 />;}            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 铅山县| 馆陶县| 家居| 大关县| 昆山市| 策勒县| 洛阳市| 通江县| 泾川县| 平安县| 无极县| 赤城县| SHOW| 叙永县| 尼玛县| 吉林市| 崇礼县| 马龙县| 全州县| 东港市| 鹤庆县| 九江县| 皋兰县| 益阳市| 高雄县| 鸡东县| 温宿县| 夏河县| 故城县| 东乡族自治县| 永城市| 沙田区| 乡城县| 长沙县| 寻乌县| 增城市| 敦煌市| 黔江区| 郁南县| 康乐县| 安丘市|