react如何导入组件
如何在React中导入组件
在React中导入组件有多种方式,具体取决于组件的导出方式以及文件的位置。
默认导出组件的导入方式
如果组件使用默认导出(export default),可以使用以下语法导入:
import ComponentName from './path/to/ComponentName';
命名导出组件的导入方式
如果组件使用命名导出(export const),需要使用花括号指定导出的名称:

import { ComponentName } from './path/to/ComponentName';
导入整个模块
也可以导入整个模块,然后通过模块名访问组件:
import * as Components from './path/to/ComponentName';
// 使用方式
<Components.ComponentName />
相对路径与绝对路径
相对路径以./或../开头,表示从当前文件位置开始查找:

import Button from '../components/Button';
使用绝对路径需要配置项目(如webpack或vite的别名alias):
import Button from '@components/Button';
动态导入(懒加载)
对于代码分割和懒加载,可以使用动态导入:
const OtherComponent = React.lazy(() => import('./OtherComponent'));
注意事项
- 确保文件扩展名正确(
.js或.jsx) - 路径区分大小写,特别是在Unix-like系统中
- 使用IDE的自动补全功能可以减少路径错误
- 在TypeScript项目中,可能需要添加
.ts或.tsx扩展名
常见目录结构示例
src/
components/
Button/
index.js
styles.css
pages/
HomePage.js
对应的导入示例:
import Button from '../components/Button';






