2 回答

TA貢獻1887條經(jīng)驗 獲得超5個贊
由于您使用的是內(nèi)部使用webpack的create-react-app,因此可以查看require-context
。這將幫助您動態(tài)導入與某個正則表達式匹配的文件夾中的所有文件。(例如:以.jsx / .js結(jié)尾)
但是,我建議您反對:
您永遠不會知道您目前正在適應的路線。
這可能會降低代碼的可讀性。
您可能還必須將組件的映射(
path
在Route中)連同組件本身一起導出。
為了避免所有這些情況,您可以index.js
在Views
組件中簡單地創(chuàng)建一個文件,該文件將需要您創(chuàng)建的任何新的路由組件,并返回在App.js
文件中形成的最終數(shù)組。
因此,本質(zhì)上是/Views/index.js:
// Import all components here
import Button from './components/Views/Button/Button';
import Color from './components/Views/Color/Color';
import Card from './components/Views/Card/Card';
import Filter from './components/Views/Filter/Filter';
const routes = [
{
path: "/",
name: 'home',
exact: true,
main: () => <h2>Home</h2>
},
{
path: "/button",
name: 'Button',
main: () => <Button />
},
{
path: "/color",
name: 'Color',
main: () => <Color />
},
{
path: "/card",
name: 'Card',
main: () => <Card />
},
{
path: "/filter",
name: 'Filter',
main: () => <Filter />
},
// add new routes here
];
export default routes;
在SideBar.js中:
import routes from 'path/to/views/Views';
//rest of your code to render the routes.
這樣,您可以清理App.js中的代碼,并且還可以有效地分離各個組件的問題。
添加回答
舉報