【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
  • 管理和注入状态

相关内容

热门资讯

推荐几款新版"pok... 推荐几款新版"pokeplus脚本,微信小程序四川微乐脚本"切实真的是有外开挂技巧-20261、打开...
专业讨论!"poke... 专业讨论!"pokernow辅助控制,微乐小程序黑科技免费"好像是真的有外开挂教程-2026运微乐小...
今天上午"约局吧如何... 今天上午"约局吧如何查看是否有挂,微信小程序怎么开挂"都是有有外开挂脚本-20261、微信小程序怎么...
信息共享"拱趴大菠萝... 信息共享"拱趴大菠萝有什么挂,微乐自建房透视"本来有有外开挂教程-20261、微乐自建房透视模拟器是...
我来分享"德州透视是... 我来分享"德州透视是真的吗,微信小程序微乐怎么才能发好牌"本来有有外开挂挂-20261)微信小程序微...
玩家必看教程!"智星... 玩家必看教程!"智星菠萝透视,微乐小程序辅助器代理"都是存在有外开挂方法-2026进入游戏-大厅左侧...
分享一款!"来玩ap... 分享一款!"来玩app破解,微乐游戏公众号辅助器"果然有有外开挂软件-20261、每一步都需要思考,...
实测分享"来玩app... 实测分享"来玩app破解版,微信微乐游戏苹果辅助器"真是有有外开挂神器-20261、玩家可以在微信微...
针对"pokemmo... 针对"pokemmo脚本辅助下载,微乐a3纸牌有脚本"好像存在有外开挂神器-2026亲,关键说明,微...
攻略讲解"佛手在线大... 攻略讲解"佛手在线大菠萝智能辅助器,微乐自建房辅助入口官网"一贯是真的有外开挂神器-2026亲,关键...