高阶组件(Higher-Order Component,HOC)是一种用于在 React 中复用组件逻辑的技术。以下是几个常见的 HOC 使用案例,以及详细的代码示例。
这个高阶组件将在每次组件更新时记录日志。
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;
// 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;
这个高阶组件在组件挂载时从一个 API 获取数据,并将数据传递给被包装的组件。
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;
// 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;
这个高阶组件根据用户权限来控制组件的渲染。
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;
// 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;
这个高阶组件根据 props 动态添加样式。
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;
// 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 中实现代码复用和逻辑抽象。通过高阶组件,你可以: