高阶组件(Higher-Order Component,HOC)是一种用于在 React 中复用组件逻辑的技术。以下是几个常见的 HOC 使用案例,以及详细的代码示例。
1. 日志记录 HOC
这个高阶组件将在每次组件更新时记录日志。
LoggingHOC.js
import React from'react';constwithLogging=(WrappedComponent)=>{returnclassextends 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}/>;}};};exportdefault withLogging;
使用日志记录 HOC
// src/App.jsimport React from'react';import withLogging from'./LoggingHOC';constMyComponent=()=>{return<div>My Component</div>;};const LoggedMyComponent =withLogging(MyComponent);constApp=()=>{return(<div><LoggedMyComponent /></div>);};exportdefault App;
2. 数据获取 HOC
这个高阶组件在组件挂载时从一个 API 获取数据,并将数据传递给被包装的组件。
FetchDataHOC.js
import React from'react';constwithFetchData=(url)=>(WrappedComponent)=>{returnclassextends React.Component {
state ={data:null,loading:true,error:null,};asynccomponentDidMount(){try{const response =awaitfetch(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}/>;}};};exportdefault withFetchData;
使用数据获取 HOC
// src/App.jsimport React from'react';import withFetchData from'./FetchDataHOC';constDataComponent=({ 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);constApp=()=>{return(<div><FetchDataComponent /></div>);};exportdefault App;
3. 权限控制 HOC
这个高阶组件根据用户权限来控制组件的渲染。
withAuthorization.js
import React from'react';constwithAuthorization=(requiredRole)=>(WrappedComponent)=>{returnclassextends 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}/>;}};};exportdefault withAuthorization;
使用权限控制 HOC
// src/App.jsimport React from'react';import withAuthorization from'./withAuthorization';constAdminPage=()=>{return<div>Admin Page</div>;};const AuthorizedAdminPage =withAuthorization('admin')(AdminPage);constApp=()=>{const user ={role:'user'};// change to 'admin' to see the pagereturn(<div><AuthorizedAdminPage user={user}/></div>);};exportdefault App;
4. 动态样式 HOC
这个高阶组件根据 props 动态添加样式。
withDynamicStyles.js
import React from'react';constwithDynamicStyles=(WrappedComponent)=>{returnclassextends React.Component {render(){const style ={color:this.props.color ||'black',fontSize:this.props.fontSize ||'16px',};return<WrappedComponent {...this.props} style={style}/>;}};};exportdefault withDynamicStyles;
使用动态样式 HOC
// src/App.jsimport React from'react';import withDynamicStyles from'./withDynamicStyles';constStyledComponent=({ style })=>{return<div style={style}>Styled Component</div>;};const DynamicStyledComponent =withDynamicStyles(StyledComponent);constApp=()=>{return(<div><DynamicStyledComponent color="red" fontSize="20px"/></div>);};exportdefault App;
总结
高阶组件是一种强大的模式,可以在 React 中实现代码复用和逻辑抽象。通过高阶组件,你可以:
- 提取和重用跨组件的逻辑
- 控制组件的渲染
- 操作传递给组件的 props
- 管理和注入状态
版权归原作者 cangloe 所有, 如有侵权,请联系我们删除。