【React】常见的 HOC 使用案例

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

1. 日志记录 HOC

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

LoggingHOC.js
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
js 复制代码
// 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
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
js 复制代码
// 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
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
js 复制代码
// 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 page
  return (
    <div>
      <AuthorizedAdminPage user={user} />
    </div>
  );
};

export default App;

4. 动态样式 HOC

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

withDynamicStyles.js
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
js 复制代码
// 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
  • 管理和注入状态
相关推荐
be or not to be13 分钟前
深入理解 CSS 浮动布局(float)
前端·css
LYFlied35 分钟前
【每日算法】LeetCode 1143. 最长公共子序列
前端·算法·leetcode·职场和发展·动态规划
老华带你飞40 分钟前
农产品销售管理|基于java + vue农产品销售管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
小徐_23331 小时前
2025 前端开源三年,npm 发包卡我半天
前端·npm·github
C_心欲无痕1 小时前
vue3 - 类与样式的绑定
javascript·vue.js·vue3
GIS之路2 小时前
GIS 数据转换:使用 GDAL 将 Shp 转换为 GeoJSON 数据
前端
JIngJaneIL2 小时前
基于springboot + vue房屋租赁管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
天天扭码2 小时前
以浏览器多进程的角度解构页面渲染的整个流程
前端·面试·浏览器
你们瞎搞2 小时前
Cesium加载20GB航测影像.tif
前端·cesium·gdal·地图切片