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 中新增元件所需的功能,並在需要時使用它。
它允許程式碼重用,並使元件僅專注於各自的任務。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP