react如何引入组件
引入组件的常见方法
直接导入默认导出组件
适用于组件文件使用 export default 导出的情况:
import ComponentName from './path/to/Component';
导入命名导出组件
适用于组件文件通过 export const 导出的情况:
import { ComponentName } from './path/to/Component';
动态导入(懒加载)
用于代码分割或按需加载场景:
const LazyComponent = React.lazy(() => import('./path/to/Component'));
// 使用时需配合Suspense
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
路径处理技巧
使用绝对路径
配置 jsconfig.json 或 tsconfig.json 避免相对路径嵌套:
{
"compilerOptions": {
"baseUrl": "src"
}
}
配置后可简化为:
import Component from 'components/Component';
别名配置
在 Webpack 或 Vite 中设置路径别名:
// vite.config.js
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
}
}
});
使用方式:
import Component from '@/components/Component';
第三方组件库引入
完整引入
适用于需要大量使用组件库的情况:
import { Button, Input } from 'antd';
按需引入
配合 babel-plugin-import 减少打包体积:
import Button from 'antd/es/button';
import 'antd/es/button/style';
类型组件引入(TypeScript)
带类型声明的导入
import type { PropsType } from './Component';
interface CustomProps extends PropsType {
additionalProp: string;
}
注意事项
- 确保文件扩展名完整(如
.jsx/.tsx) - 循环引用可能导致模块未定义错误
- 动态导入的组件需考虑加载状态处理
- 生产环境建议启用 tree-shaking 优化







