react如何模块化
React 模块化方法
组件化开发
将 UI 拆分为独立、可复用的组件,每个组件负责特定功能。组件通过 props 传递数据,通过 state 管理内部状态。例如:
// Button.jsx
const Button = ({ onClick, children }) => {
return <button onClick={onClick}>{children}</button>;
};
export default Button;
文件结构组织
按功能或路由划分模块,常见结构如下:

src/
├── components/ # 通用组件
├── features/ # 功能模块(如用户管理)
├── hooks/ # 自定义 Hook
├── utils/ # 工具函数
└── App.js # 主入口
状态管理模块化
使用 Context API 或 Redux 管理全局状态,避免状态分散。Redux 示例:
// store/userSlice.js
const userSlice = createSlice({
name: 'user',
initialState: { name: '' },
reducers: { /* ... */ }
});
export const { actions, reducer } = userSlice;
动态导入与代码分割
通过 React.lazy 和 Suspense 实现按需加载,减少初始包体积:

const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<Spinner />}>
<LazyComponent />
</Suspense>
);
}
自定义 Hook 复用逻辑
将重复逻辑封装为 Hook,例如数据获取:
// hooks/useFetch.js
function useFetch(url) {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url).then(res => res.json()).then(setData);
}, [url]);
return data;
}
CSS 模块化
使用 CSS Modules 或 styled-components 避免样式冲突:
// Button.module.css
.button { background: blue; }
// Button.jsx
import styles from './Button.module.css';
const Button = () => <button className={styles.button}>Click</button>;






