React常見的?HOC?使用案例及示例代碼
高階組件(Higher-Order Component,HOC)是一種用于在 React 中復(fù)用組件邏輯的技術(shù)。以下是幾個(gè)常見的 HOC 使用案例,以及詳細(xì)的代碼示例。
1. 日志記錄 HOC
這個(gè)高階組件將在每次組件更新時(shí)記錄日志。
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. 數(shù)據(jù)獲取 HOC
這個(gè)高階組件在組件掛載時(shí)從一個(gè) API 獲取數(shù)據(jù),并將數(shù)據(jù)傳遞給被包裝的組件。
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;使用數(shù)據(jù)獲取 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. 權(quán)限控制 HOC
這個(gè)高階組件根據(jù)用戶權(quán)限來控制組件的渲染。
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;使用權(quán)限控制 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 page
return (
<div>
<AuthorizedAdminPage user={user} />
</div>
);
};
export default App;4. 動(dòng)態(tài)樣式 HOC
這個(gè)高階組件根據(jù) props 動(dòng)態(tài)添加樣式。
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;使用動(dòng)態(tài)樣式 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;總結(jié)
高階組件是一種強(qiáng)大的模式,可以在 React 中實(shí)現(xiàn)代碼復(fù)用和邏輯抽象。通過高階組件,你可以:
- 提取和重用跨組件的邏輯
- 控制組件的渲染
- 操作傳遞給組件的 props
- 管理和注入狀態(tài)
到此這篇關(guān)于React常見的 HOC 使用案例的文章就介紹到這了,更多相關(guān)React HOC 使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
react使用antd-design中select不能及時(shí)刷新問題及解決
這篇文章主要介紹了react使用antd-design中select不能及時(shí)刷新問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03
React報(bào)錯(cuò)之Object?is?possibly?null的問題及解決方法
這篇文章主要介紹了React報(bào)錯(cuò)之Object?is?possibly?null的問題,造成 "Object is possibly null"的錯(cuò)誤是因?yàn)閡seRef()鉤子可以傳遞一個(gè)初始值作為參數(shù),而我們傳遞null作為初始值,本文給大家分享詳細(xì)解決方法,需要的朋友可以參考下2022-07-07
React中組件的this.state和setState的區(qū)別
在React開發(fā)中,this.state用于初始化和讀取組件狀態(tài),而setState()用于安全地更新狀態(tài),正確使用這兩者對(duì)于管理React組件狀態(tài)至關(guān)重要,避免性能問題和常見錯(cuò)誤2024-09-09
React項(xiàng)目中className運(yùn)用及問題解決
這篇文章主要為大家介紹了React項(xiàng)目中className運(yùn)用及問題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
React onClick/onChange傳參(bind綁定)問題
這篇文章主要介紹了React onClick/onChange傳參(bind綁定)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02
react 移動(dòng)端實(shí)現(xiàn)列表左滑刪除的示例代碼
這篇文章主要介紹了react 移動(dòng)端實(shí)現(xiàn)列表左滑刪除的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
一文教你如何避免React中常見的8個(gè)錯(cuò)誤
這篇文章主要來和大家一起分享在?React?開發(fā)中常見的一些錯(cuò)誤,以及如何避免這些錯(cuò)誤,理解這些問題背后的細(xì)節(jié),防止犯下類似的錯(cuò)誤,需要的可以參考下2023-12-12

