react如何扩展
扩展 React 应用的方法
使用高阶组件(HOC)
高阶组件是一种函数,接收组件并返回增强后的新组件。常用于复用逻辑,如权限控制、日志记录等。示例:
function withLogging(WrappedComponent) {
return function(props) {
console.log('Rendered:', WrappedComponent.name);
return <WrappedComponent {...props} />;
};
}
const EnhancedComponent = withLogging(MyComponent);
自定义 Hook
通过自定义 Hook 封装可复用的状态逻辑。适用于跨组件共享逻辑,如数据获取、表单处理等。示例:
function useFetch(url) {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url).then(res => res.json()).then(setData);
}, [url]);
return data;
}
// 使用
const data = useFetch('/api/data');
组合组件模式
通过 children 或 props 组合组件,增强灵活性。例如构建可复用的布局组件:

function Layout({ header, content }) {
return (
<div>
<div className="header">{header}</div>
<div className="content">{content}</div>
</div>
);
}
// 使用
<Layout header={<Header />} content={<MainContent />} />
使用 Context API
通过 React.createContext 共享全局状态,避免多层 props 传递。适用于主题、用户信息等场景。示例:
const ThemeContext = React.createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
// 子组件消费
const theme = useContext(ThemeContext);
集成状态管理库
对于复杂状态逻辑,可引入 Redux、MobX 或 Zustand。Redux 示例:

import { createStore } from 'redux';
const store = createStore(reducer);
// 组件中连接
const mapStateToProps = state => ({ count: state.count });
connect(mapStateToProps)(MyComponent);
代码分割与懒加载
使用 React.lazy 和 Suspense 实现按需加载,优化性能。示例:
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<Spinner />}>
<LazyComponent />
</Suspense>
);
}
类型检查与 PropTypes
通过 TypeScript 或 prop-types 增强代码健壮性。TypeScript 示例:
interface Props {
title: string;
size?: 'sm' | 'md';
}
function Button({ title, size = 'md' }: Props) {
return <button className={size}>{title}</button>;
}
性能优化
使用 React.memo、useMemo 或 useCallback 避免不必要的渲染。示例:
const MemoizedComponent = React.memo(MyComponent);
function Parent() {
const handleClick = useCallback(() => {}, []);
return <MemoizedComponent onClick={handleClick} />;
}






