【React】常见的 HOC 使用案例

devtools/2024/10/21 4:44:17/

高阶组件(Higher-Order Component,HOC)是一种用于在 React 中复用组件逻辑的技术。以下是几个常见的 HOC 使用案例,以及详细的代码示例。

1. 日志记录 HOC

这个高阶组件将在每次组件更新时记录日志。

LoggingHOC.js
import React from 'react';const withLogging = (WrappedComponent) => {return class extends React.Component {componentDidMount() {console.log(`${WrappedComponent.name} mounted`);}componentDidUpdate() {console.log(`${WrappedComponent.name} updated`);}componentWillUnmount() {console.log(`${WrappedComponent.name} will unmount`);}render() {return <WrappedComponent {...this.props} />;}};
};export default withLogging;
使用日志记录 HOC
// src/App.js
import React from 'react';
import withLogging from './LoggingHOC';const MyComponent = () => {return <div>My Component</div>;
};const LoggedMyComponent = withLogging(MyComponent);const App = () => {return (<div><LoggedMyComponent /></div>);
};export default App;

2. 数据获取 HOC

这个高阶组件在组件挂载时从一个 API 获取数据,并将数据传递给被包装的组件。

FetchDataHOC.js
import React from 'react';const withFetchData = (url) => (WrappedComponent) => {return class extends React.Component {state = {data: null,loading: true,error: null,};async componentDidMount() {try {const response = await fetch(url);const data = await response.json();this.setState({ data, loading: false });} catch (error) {this.setState({ error, loading: false });}}render() {const { data, loading, error } = this.state;return <WrappedComponent data={data} loading={loading} error={error} {...this.props} />;}};
};export default withFetchData;
使用数据获取 HOC
// src/App.js
import React from 'react';
import withFetchData from './FetchDataHOC';const DataComponent = ({ data, loading, error }) => {if (loading) return <div>Loading...</div>;if (error) return <div>Error: {error.message}</div>;return <div>Data: {JSON.stringify(data)}</div>;
};const FetchDataComponent = withFetchData('https://api.example.com/data')(DataComponent);const App = () => {return (<div><FetchDataComponent /></div>);
};export default App;

3. 权限控制 HOC

这个高阶组件根据用户权限来控制组件的渲染。

withAuthorization.js
import React from 'react';const withAuthorization = (requiredRole) => (WrappedComponent) => {return class extends React.Component {render() {const { user } = this.props;if (user.role !== requiredRole) {return <div>You do not have permission to view this page</div>;}return <WrappedComponent {...this.props} />;}};
};export default withAuthorization;
使用权限控制 HOC
// src/App.js
import React from 'react';
import withAuthorization from './withAuthorization';const AdminPage = () => {return <div>Admin Page</div>;
};const AuthorizedAdminPage = withAuthorization('admin')(AdminPage);const App = () => {const user = { role: 'user' }; // change to 'admin' to see the pagereturn (<div><AuthorizedAdminPage user={user} /></div>);
};export default App;

4. 动态样式 HOC

这个高阶组件根据 props 动态添加样式。

withDynamicStyles.js
import React from 'react';const withDynamicStyles = (WrappedComponent) => {return class extends React.Component {render() {const style = {color: this.props.color || 'black',fontSize: this.props.fontSize || '16px',};return <WrappedComponent {...this.props} style={style} />;}};
};export default withDynamicStyles;
使用动态样式 HOC
// src/App.js
import React from 'react';
import withDynamicStyles from './withDynamicStyles';const StyledComponent = ({ style }) => {return <div style={style}>Styled Component</div>;
};const DynamicStyledComponent = withDynamicStyles(StyledComponent);const App = () => {return (<div><DynamicStyledComponent color="red" fontSize="20px" /></div>);
};export default App;

总结

高阶组件是一种强大的模式,可以在 React 中实现代码复用和逻辑抽象。通过高阶组件,你可以:

  • 提取和重用跨组件的逻辑
  • 控制组件的渲染
  • 操作传递给组件的 props
  • 管理和注入状态

http://www.ppmy.cn/devtools/87681.html

相关文章

python I 嵌套列表的多种展开方法

python中&#xff0c;如何将嵌套列表展开形成一个列表。 一、嵌套列表格式 本文模拟的嵌套列表alis&#xff0c;如下&#xff1a; alis [[xx, yy], [2], [四, 4], [99]]嵌套列表alis&#xff0c;有以下特点&#xff1a; 1、嵌套列表alis&#xff0c;只有两层&#xff0c;格…

环境如何搭建部署Nacos

这里我使用的是Centos7&#xff0c; Nacos 依赖 Java环境来运行。如果您是从代码开始构建并运行Nacos&#xff0c;还需要为此配置 Maven环境&#xff0c;请确保是在以下版本环境中安装使用 ## 1、下载安装JDK wget https://download.oracle.com/java/17/latest/jdk-17_linux-x6…

Mysql重大更新,三个版本遭下架!

书接上文&#xff0c;7/11日开源数据库软件服务商percona发布重要警告&#xff0c;最新的mysql版本存在重大bug&#xff0c; 当mysql表超过10000张时重启可能会崩溃 重要&#xff01;&#xff01;&#xff01;MySQL 9.0存在重大BUG&#xff01;&#xff01;_mysql8.0.38 版本…

视觉SLAM第二讲

SLAM分为定位和建图两个问题。 定位问题 定位问题是通过传感器观测数据直接或间接求解位置和姿态。 通常可以分为两类&#xff1a;基于已知地图的定位和基于未知地图的定位。 基于已知地图的定位 利用预先构建的地图&#xff0c;结合传感器数据进行全局定位。SLAM中的全局…

EF访问PostgreSql,如何判断jsonb类型的数组是否包含某个数值

下面代码判断OpenUserIds&#xff08;long[]类型的jsonb&#xff09;字段&#xff0c;是否包含 8 basequery basequery.Where(m > Microsoft.EntityFrameworkCore.NpgsqlJsonDbFunctionsExtensions.JsonContains(EF.Functions, m.OpenUserIds, new long[] { 8 }));

昇思25天学习打卡营第XX天|LSTM+CRF序列标注

条件随机场&#xff08;CRF&#xff09;是一种用于序列预测的概率图模型&#xff0c;它考虑了序列中元素之间的相互依赖关系。与简单的多分类问题不同&#xff0c;CRF能够捕捉序列中标签的连贯性&#xff0c;如在命名实体识别中&#xff0c;一个词的标签往往依赖于它前面词的标…

SA后缀数组

基础概念&#xff1a; 子串&#xff1a; 在一个字符串s中&#xff0c;取任意i<j,那么从i到j的这一段就叫做s的一个子串 后缀&#xff1a; 从字符串s的某个位置i到字符串末尾的子串&#xff0c; suff[i]: 以s的第i个字符为第一个元素的后缀 后缀数组&#xff1a; 现有字符…

Android 10.0 Launcher 启动流程

在前面SystemUI启动流程中说到&#xff0c;在SystemServer中会去启动各种系统服务&#xff0c;这里的launcher也是启动的其中一个服务ActivityManagerService去启动的。在android10之前&#xff0c;系统四大组件的启动都是在ActivityManagerService中&#xff0c;在android10中…