React JS中如何在单个文件内导出多个类组件?
在单个React文件中导出多个组件的方法
嘿,作为React新手想把所有组件都放在一个文件里完全没问题!我给你几种简单易懂的方法,结合你的示例代码来演示,马上就能上手~
方法一:直接命名导出(最常用)
你可以在每个组件的定义前面加上export关键字,这样就可以直接把组件作为命名导出暴露出去。比如:
import React, { Component } from "react"; // 给类组件加上export,直接命名导出 export class MyText extends Component { render() { return ( <div> <h1>MyText Component</h1> <p>This class component is named MyText. I can re-use it's code by simply Rendering it by it's class name and I won't have to re type it, however many times I will need it.</p> </div> ); } } // 再写一个函数组件,同样用命名导出 export function MyButton() { return <button>Click Me!</button>; }
在其他文件使用的时候,需要用花括号导入对应的组件:
// 导入指定的多个组件 import { MyText, MyButton } from './YourComponentFileName'; // 然后就能直接在代码里使用啦 function App() { return ( <div> <MyText /> <MyButton /> </div> ); }
方法二:默认导出 + 命名导出混合
如果你的文件里有一个主要组件,其他是辅助组件,可以把主组件设为默认导出,剩下的用命名导出。比如:
import React, { Component } from "react"; // 先定义组件,不着急导出 class MyText extends Component { render() { return ( <div> <h1>MyText Component</h1> <p>This class component is named MyText. I can re-use it's code by simply Rendering it by it's class name and I won't have to re type it, however many times I will need it.</p> </div> ); } } function MyButton() { return <button>Click Me!</button>; } // 将MyText设为默认导出,同时命名导出MyButton export default MyText; export { MyButton };
导入的时候,默认组件不用加花括号,命名组件还是要加:
// 默认导入MyText,花括号导入MyButton import MyText, { MyButton } from './YourComponentFileName';
方法三:文件末尾统一导出
如果你不想在每个组件前面加export,可以先把所有组件都定义好,最后在文件末尾统一导出:
import React, { Component } from "react"; // 先定义所有组件 class MyText extends Component { render() { return ( <div> <h1>MyText Component</h1> <p>This class component is named MyText. I can re-use it's code by simply Rendering it by it's class name and I won't have to re type it, however many times I will need it.</p> </div> ); } } function MyButton() { return <button>Click Me!</button>; } // 统一导出多个组件 export { MyText, MyButton };
这种方式的导入和方法一完全一样,用花括号指定要导入的组件即可。
小提示
如果导入的时候想给组件改个名字,可以用as关键字:
// 把MyText重命名为TextComponent import { MyText as TextComponent, MyButton } from './YourComponentFileName'; // 使用的时候就用新名字 function App() { return ( <div> <TextComponent /> <MyButton /> </div> ); }
内容的提问来源于stack exchange,提问作者Tony Carbetta
相关产品推荐
相关产品推荐

