【React】常见的 HOC 使用案例
创始人
2024-11-12 19:08:18
0

高阶组件(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 ...this.props} />;     }   }; };  export default withLogging; 
使用日志记录 HOC
// src/App.js import React from 'react'; import withLogging from './LoggingHOC';  const MyComponent = () => {   return 
My Component
; }; const LoggedMyComponent = withLogging(MyComponent); const App = () => { return (
); }; 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 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 
Loading...
; if (error) return
Error: {error.message}
; return
Data: {JSON.stringify(data)}
; }; const FetchDataComponent = withFetchData('https://api.example.com/data')(DataComponent); const App = () => { return (
); }; 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 
You do not have permission to view this page
; } return ...this.props} />; } }; }; export default withAuthorization;
使用权限控制 HOC
// src/App.js import React from 'react'; import withAuthorization from './withAuthorization';  const AdminPage = () => {   return 
Admin Page
; }; const AuthorizedAdminPage = withAuthorization('admin')(AdminPage); const App = () => { const user = { role: 'user' }; // change to 'admin' to see the page return (
user} />
); }; 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 ...this.props} style={style} />;     }   }; };  export default withDynamicStyles; 
使用动态样式 HOC
// src/App.js import React from 'react'; import withDynamicStyles from './withDynamicStyles';  const StyledComponent = ({ style }) => {   return 
style}>Styled Component
; }; const DynamicStyledComponent = withDynamicStyles(StyledComponent); const App = () => { return (
); }; export default App;

总结

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

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

相关内容

热门资讯

黑科技科技(aaPoker)外... 黑科技科技(aaPoker)外挂透明挂辅助挂(软件透明挂)的确真的有挂(2025已更新)(哔哩哔哩)...
黑科技机制(鱼扑克app)外挂... 黑科技机制(鱼扑克app)外挂透明挂辅助透视(黑科技)一贯真的有挂(2022已更新)(哔哩哔哩);1...
黑科技自建房(德扑线上)外挂透... 黑科技自建房(德扑线上)外挂透明挂辅助透视(透视)就是真的有挂(2020已更新)(哔哩哔哩)1、透视...
透视针对(Wpk)外挂透明挂辅... 透视针对(Wpk)外挂透明挂辅助安装(透视)果然真的有挂(2023已更新)(哔哩哔哩)1、机器人多个...
黑科技计算器(哈糖大菠萝)外挂... 黑科技计算器(哈糖大菠萝)外挂透明挂辅助安装(透视)好像真的有挂(2021已更新)(哔哩哔哩)1、黑...
黑科技存在(智星德州扑克)外挂... 黑科技存在(智星德州扑克)外挂透明挂辅助脚本(软件透明挂)就是真的有挂(2022已更新)(哔哩哔哩)...
透视工具(WPK)外挂透明挂辅... 透视工具(WPK)外挂透明挂辅助挂(辅助挂)一般真的有挂(2022已更新)(哔哩哔哩)1、实时开挂更...
黑科技开挂(约局吧)外挂透明挂... 黑科技开挂(约局吧)外挂透明挂辅助神器(透明挂)果真真的有挂(2021已更新)(哔哩哔哩)1、让任何...
黑科技机制(手机德州)外挂透明... 黑科技机制(手机德州)外挂透明挂辅助app(透视辅助)的确真的有挂(2023已更新)(哔哩哔哩);暗...
黑科技ai代打(wepoker... 黑科技ai代打(wepoker)外挂透明挂辅助透视(黑科技)果真真的有挂(2025已更新)(哔哩哔哩...