【问题标题】:Nested Routes in REACT ROUTER DOM, wrapping Components in RouterREACT ROUTER DOM 中的嵌套路由,将组件包装在路由器中
【发布时间】:2018-05-30 11:38:11
【问题描述】:

我有 2 个组件,我想要一个组件在某些路由中通用,而其他组件在其余路由中通用。

在这两个组件中,我在两个组件中都使用 {props.children} 作为嵌套路由。

我的代码是:

<Router history={history}>
  <div className='routeContainer'>
    <Switch>

      <Component1>
        <Route exact path='/' component={Dashboard} />
        <Route exact path='/abc' component={ComponentAbc} />
      </Component1>

      <Component2>
        <Route exact path='/def' component={ComponentDEF} />
        <Route exact path='/xyz' component={ComponentXYZ} />
      </Component2>
    </Switch>
  </div>
</Router>

在组件 1 和组件 2 中,我使用的是 {this.props.children} 如下:

render () {
 return (
  <div>

      <SideBar />
      <Header />
      {this.props.children} 
  </div>
 )
}

这不工作,请帮助使这个结构工作。

【问题讨论】:

    标签: reactjs routing react-router-v4 react-router-dom


    【解决方案1】:

    &lt;Switch&gt; 的所有子元素都应该是 &lt;Route&gt;&lt;Redirect&gt; 元素。 只有与当前位置匹配的第一个孩子才会被渲染。" - react-router

    如果您想要路由组件的父级,您可以执行以下操作之一:

    1. 在组件内包装
    2. 包裹在 RouteProps - 组件内

    无论哪种方式,您都需要删除除&lt;Routes/&gt;&lt;Redirects/&gt;&lt;Switch&gt; 之外的所有内容

    替代示例2

    <Route exact path='/' component={()=> (
      <Component1>
        <Dashboard />
      </Component1>  
    )} />
    

    【讨论】:

      猜你喜欢
      • 2018-05-26
      • 2021-12-30
      • 2017-04-24
      • 2020-10-14
      • 2020-10-10
      • 2017-08-16
      • 2022-01-13
      • 2015-02-21
      • 1970-01-01
      相关资源
      最近更新 更多