【问题标题】:ReactJs dynamic component render with dynamic routesReactJs 动态组件渲染与动态路由
【发布时间】:2021-09-30 23:17:20
【问题描述】:

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

<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>

如何根据选择的application 动态渲染Home 中的组件,然后通过button click 路由到dynamic routes 及其dynamic components?我是 ReactJs 的新手,不知道该怎么做。

【问题讨论】:

    标签: javascript reactjs dynamic react-router


    【解决方案1】:

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

    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>
    

    【讨论】:

      猜你喜欢
      • 2020-09-02
      • 1970-01-01
      • 2019-11-26
      • 2016-02-24
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 2022-06-12
      相关资源
      最近更新 更多