react如何引用组件
引用组件的方法
在React中引用组件主要有两种方式:通过默认导出(Default Export)和命名导出(Named Export)。以下是具体实现方法:
默认导出方式
组件文件(如MyComponent.js)使用export default导出:
// MyComponent.js
function MyComponent() {
return <div>Hello World</div>;
}
export default MyComponent;
引用时直接导入:
import MyComponent from './MyComponent';
命名导出方式
组件文件使用命名导出(可导出多个组件):
// Components.js
export function Button() { /* ... */ }
export function Input() { /* ... */ }
引用时通过解构导入:
import { Button, Input } from './Components';
动态引用组件
使用React.lazy和Suspense实现动态加载(适用于代码分割):
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<React.Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</React.Suspense>
);
}
高阶组件(HOC)引用
通过高阶组件包装目标组件:
function withLogging(WrappedComponent) {
return function(props) {
console.log('Rendered:', WrappedComponent.name);
return <WrappedComponent {...props} />;
};
}
const EnhancedComponent = withLogging(MyComponent);
注意事项
- 组件文件扩展名建议使用
.jsx或.tsx(TypeScript) - 引用路径需注意相对路径(
./)和绝对路径(配置jsconfig.json或webpack别名) - 循环引用可能导致问题,需通过惰性加载或重构组件结构解决






