react如何引入组件
引入组件的常见方法
直接导入组件文件
通过import语句从指定路径引入组件文件,适用于项目内自定义组件。假设组件文件位于./components/Button.js:
import Button from './components/Button';
通过相对路径或别名导入
若项目配置了路径别名(如Webpack的resolve.alias),可使用别名简化路径:
import Button from '@components/Button'; // 假设@components已配置为./src/components
默认导出与命名导出的区别
组件文件若使用export default,导入时无需花括号;若使用命名导出(如export const Button),则需明确指定:
import { Button } from './components/Button'; // 命名导出
动态导入(按需加载)
使用React.lazy实现懒加载
适用于路由级组件或性能优化场景,需配合Suspense使用:

const LazyComponent = React.lazy(() => import('./components/LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
动态导入结合条件渲染
通过逻辑判断动态决定加载的组件:
let Component;
if (condition) {
Component = React.lazy(() => import('./components/A'));
} else {
Component = React.lazy(() => import('./components/B'));
}
第三方库组件的引入
从npm包导入
通过包名直接引入已安装的第三方组件库(如Material-UI):

import { Button } from '@mui/material';
全局组件注册(不推荐)
部分库允许全局注册组件(如Vue风格),但在React中通常避免此模式,因其破坏模块化。
注意事项
文件扩展名处理
现代构建工具(如Vite)通常允许省略.js/.jsx扩展名,但需确保项目配置支持。
循环依赖问题
避免组件间相互导入导致循环依赖,可通过状态提升或重构组件结构解决。
TypeScript支持
若使用TypeScript,需确保组件文件包含类型定义或配套的.d.ts声明文件。






