React.js 中的高阶组件

react jsjavascript libraryfront end technology更新于 2025/11/7 2:52:17

高阶组件简称 hoc。它是一种接收一个组件并返回一个包含附加功能的新组件的模式。

//hoc 是一个自定义 JavaScript 函数的名称

const AddOnComponent= hoc(SimpleComponent);

我们使用带有 state 和/或 props 的组件来构建 UI。类似地,hoc 会根据提供的组件构建一个新组件。

在 React 中使用 hoc 可以创建横切关注点。组件负责单个任务的职责,而 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 包装,该 userSpecificMessage 从包装组件(即 UserComponent)接收 props。

hoc userSpecificMessage 根据用户类型决定显示哪条消息。

如果用户类型为客户,则按原样显示消息。但如果用户不是客户,则默认显示"欢迎管理员"消息。

通过这种方式,我们可以在 hoc 中添加组件所需的通用功能,并在需要时使用。

它允许代码重用,并使组件保持简洁,只包含单个任务。


相关文章


有用资源