react如何引用其他组件
引用组件的基本方法
在React中引用其他组件通常通过import语句实现。假设有一个名为Button的组件,文件路径为./components/Button.js:
import Button from './components/Button';
function App() {
return (
<div>
<Button />
</div>
);
}
默认导出与命名导出
如果组件使用默认导出(export default),引用时可以直接使用任意名称。若组件使用命名导出(如export const Button),则需要用花括号明确指定:
import { Button } from './components/Button';
动态导入(懒加载)
对于性能优化,可以使用React.lazy实现组件的动态加载:
const LazyComponent = React.lazy(() => import('./components/LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
跨项目引用
通过npm安装的第三方组件库,引用方式与本地组件类似:
import { Icon } from 'antd';
组件传递与组合
通过props可以将组件作为参数传递给其他组件:
function Card({ children }) {
return <div className="card">{children}</div>;
}
function App() {
return (
<Card>
<Button />
</Card>
);
}
注意事项
确保组件文件扩展名正确(如.jsx或.js),路径需相对于当前文件。TypeScript项目中还需检查类型定义是否正确导出。







