我正在使用react-router进行项目。
这是一个项目结构
main
- mainRouter.tsx
- programFolder
- ProgramMainComponent.tsx
- ProgramScheduleComponent.tsx
- ProgramDetailComponent.tsx
- programRouter.tsx
- serviceFolder
- ServiceMainComponent.tsx
- ServiceFAQComponent.tsx
- ServiceCustomerComponent.tsx
- serviceRouter.tsx
这就是我制作programRouter.tsx和serviceRouter.tsx
的方式// programRouter.tsx
const ProgramRouter = () => {
return (
<BrowserRouter>
<Switch>
<Route path={'/program'} exact={true} component={ProgramMainComponent} />
<Route path={'/program/schedule'} exact={true} component={ProgramScheduleComponent} />
<Route path={'/program/detail'} exact={true} component={ProgramDetailComponent} /
</Switch>
</BrowserRouter>
)
}
// serviceRouter.tsx
const ServiceRouter = () => {
return (
<BrowserRouter>
<Switch>
<Route path={'/service'} exact={true} component={ServiceMainComponent} />
<Route path={'/service/faq'} exact={true} component={ServiceFAQComponent} />
<Route path={'/program/customer'} exact={true} component={ServiceCustomerComponent} />
</Switch>
</BrowserRouter>
)
}
这就是我想要做的。
随着我添加更多页面,我希望每个文件夹都包含各自的router.tsx文件,并将这些文件导入mainRouter.tsx文件内部,如下例所示。
import * as React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { programRouter } from 'main/program';
import { serviceRouter } from 'main/service';
const Router = () => {
return (
<BrowserRouter>
<Switch>
<Route path='/' exact={true} component={MainComponent} />
<Route path={'/program'} exact={true} component={programRouter} />
<Route path={'/service'} exact={true} component={serviceRouter} />
</Switch>
</BrowserRouter>
)
}
是否可以使用mainRouter.tsx中的每个路由器组件?
答案 0 :(得分:0)
React Router docs中有一个嵌套组件和路由的示例。基本上,您不需要在根级别多次使用BrowserRouter
。您还应该删除根组件中路线的exact={true}
道具,以确保其子路线可以正确呈现。
import * as React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { programRouter } from 'main/program';
import { serviceRouter } from 'main/service';
const Router = () => {
return (
<BrowserRouter>
<Switch>
<Route path='/' exact component={MainComponent} />
<Route path={'/program'} component={programRouter} />
<Route path={'/service'} component={serviceRouter} />
</Switch>
</BrowserRouter>
)
}