首页 > 解决方案 > ReactJs 动态组件渲染与动态路由

问题描述

在我的项目中,根据用户选择的应用程序类型,组件必须渲染并进一步导航到不同的路线。在所有这些应用程序中,布局保持不变。我必须根据路线添加不同的组件。首页主要组件

<Card>
<Card.Body>
<DYNAMIC_COMPONENT /> //based on application chosen
<button onClick={()=> takeToNextRoute}>CLICK ME</button>
<Card.body>
</Card>

基于按钮点击Home,用户将被带到不同的路线Application type

<div>
<Router>
<Switch>
<Route exact path='/:{based on app}' component={dynamicCOMP}></Route>
<Route exact path='/about:{based on app}' component={dynamicCOMP1}></Route>
<Route exact path='/profile:{based on app}' component={dynamicCOMP2}></Route>
<Route exact path='/select:{based on app}' component={dynamicCOMP3}></Route>
</Switch>
</Router>
</div>

如何Home根据application选择的动态渲染组件,然后使用它的button click路由?我是 ReactJs 的新手,不知道如何去做。dynamic routesdynamic components

标签: javascriptreactjsdynamicreact-router

解决方案


您可以拥有一个包含所有路由和组件的对象:

const routes = {
  "/": HomeComponent,
  "/about": AboutComponent,
  "/profile": ProfileComponent,
  "/select": SelectComponent
}

然后在你的路由器中,它看起来像:

<div>
<Router>
<Switch>
{Object.keys(routes).map((route, i) => <Route key = {i} exact path = {route} component = {routes[route]}/>
</Switch>
</Router>
</div>

推荐阅读