React常見的?HOC?使用案例及示例代碼
高階組件(Higher-Order Component,HOC)是一種用于在 React 中復用組件邏輯的技術(shù)。以下是幾個常見的 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. 數(shù)據(jù)獲取 HOC
這個高階組件在組件掛載時從一個 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
這個高階組件根據(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. 動態(tài)樣式 HOC
這個高階組件根據(jù) props 動態(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;
使用動態(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é)
高階組件是一種強大的模式,可以在 React 中實現(xiàn)代碼復用和邏輯抽象。通過高階組件,你可以:
- 提取和重用跨組件的邏輯
- 控制組件的渲染
- 操作傳遞給組件的 props
- 管理和注入狀態(tài)
到此這篇關(guān)于React常見的 HOC 使用案例的文章就介紹到這了,更多相關(guān)React HOC 使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
react使用antd-design中select不能及時刷新問題及解決
這篇文章主要介紹了react使用antd-design中select不能及時刷新問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03React報錯之Object?is?possibly?null的問題及解決方法
這篇文章主要介紹了React報錯之Object?is?possibly?null的問題,造成 "Object is possibly null"的錯誤是因為useRef()鉤子可以傳遞一個初始值作為參數(shù),而我們傳遞null作為初始值,本文給大家分享詳細解決方法,需要的朋友可以參考下2022-07-07React中組件的this.state和setState的區(qū)別
在React開發(fā)中,this.state用于初始化和讀取組件狀態(tài),而setState()用于安全地更新狀態(tài),正確使用這兩者對于管理React組件狀態(tài)至關(guān)重要,避免性能問題和常見錯誤2024-09-09React onClick/onChange傳參(bind綁定)問題
這篇文章主要介紹了React onClick/onChange傳參(bind綁定)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02