React.js 中的高階元件


高階元件,簡稱 hoc。它是一種模式,接收一個元件並返回一個新的元件,並在其上新增附加功能。

//hoc 是一個自定義 JavaScript 函式的名稱

const AddOnComponent= hoc(SimpleComponent);

我們使用帶有狀態和/或 props 的元件來構建 UI。類似地,hoc 從提供的元件構建一個新的元件。

hoc 的用途是在 React 中進行橫切關注點。元件將負責單個任務的單個職責,而 hoc 函式將負責橫切關注點。

來自 redux 的 Connect 函式是 hoc 的一個例子。

hoc 的一個實際例子

根據使用者型別向客戶或管理員顯示歡迎訊息。

Class App extends React.Component{
   render(){
      return (
         <UserWelcome message={this.props.message} userType={this.props.userType} />
      );
   }
}
Class UserWelcome extends React.Component{
   render(){
      return(
         <div>Welcome {this.props.message}</div>
      );
   }
}
const userSpecificMessage=(WrappedComponent)=>{
   return class extends React.Component{
      render(){
         if(this.props.userType==’customer’){
         return(
            <WrappedComponent {…this.props}/>
         );
         } else {
            <div> Welcome Admin </div>
         }
      }
   }
}

export default userSpecificMessage(UserWelcome)

在 UserWelcome 中,我們只是向父元件 App.js 傳遞的使用者顯示訊息。

UserComponent 被 hoc userSpecificMessage 包裹,後者從被包裹的元件即 UserComponent 接收 props。

hoc userSpecificMessage 根據使用者型別決定顯示哪個訊息。

如果使用者型別是客戶,則按原樣顯示訊息。但如果使用者不是客戶,則預設顯示歡迎管理員訊息。

透過這種方式,我們可以在 hoc 中新增元件所需的功能,並在需要時使用它。

它允許程式碼重用,並使元件僅專注於各自的任務。

更新於: 2019-09-05

164 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.