react页面如何实现复用
复用 React 页面的方法
组件化拆分
将页面拆分为独立的组件,例如头部、侧边栏、内容区等。每个组件通过 props 接收数据,实现逻辑与 UI 分离。适合重复使用的 UI 部分(如按钮、卡片)可以抽象为通用组件。
高阶组件(HOC)
通过高阶组件包裹现有组件,注入共享逻辑(如权限校验、数据加载)。例如:
const withAuth = (WrappedComponent) => {
return (props) => {
const isAuthenticated = checkAuth();
return isAuthenticated ? <WrappedComponent {...props} /> : <Redirect to="/login" />;
};
};
自定义 Hook
将可复用的状态逻辑提取为自定义 Hook。例如封装数据获取逻辑:
function useFetchData(url) {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url).then(res => res.json()).then(setData);
}, [url]);
return data;
}
Render Props 模式
通过组件属性传递渲染函数,共享组件间的代码。例如:
<DataProvider render={data => <Page data={data} />} />
动态路由与布局组件
使用 React Router 配置动态路由参数,结合共享的布局组件减少重复代码:
<Route path="/posts/:id" component={PostLayout} />
Context API
跨层级组件共享数据时,使用 React.createContext 提供全局状态,避免逐层传递 props。
代码分割与懒加载
通过 React.lazy 和 Suspense 实现组件按需加载,优化复用时的性能:
const LazyComponent = React.lazy(() => import('./LazyComponent'));
注意事项
- 避免过度抽象,确保复用组件具有明确的单一职责。
- 优先组合而非继承,React 官方推荐组合模式实现复用。
- 使用 TypeScript 或 PropTypes 规范
props类型,提升可维护性。







