繁体   English   中英

如何在React Router 4/5中有条件地呈现包装组件

[英]How to conditionally render wrapping components in React Router 4/5

我正在将一个应用程序从react-router版本3迁移到5,并且我试图找出解决以下问题的最佳方法。

我有一些使用包装组件的路线。

在routerv3我可以做的事情

const Container = props => 
  <div>
    <header>container1</header>
    { props.children } 
  </div>

const Container2 = props => 
  <div>
    <header>container2</header>
    { props.children } 
  </div>

这些容器具有其他功能

<Route component={Container}>
  <Route path='/container1' component={Page1} />
</Route>

<Route component={Container2}>
  <Route path='/container2' component={Page1} />
</Route>

当导航到/container1 ,它将使用包装它的Container1呈现Page1组件,然后在/container2它将使用包装它的Container2呈现Page1

然而,当移动到路由器v4 +所有匹配的路由都被渲染时,所发生的是例如在/container2的结果是

<div>
  <header>container1</header>
</div>
<div>
  <header>container2</header> 
  <Page1 />
</div>

有没有人知道编写这些“包装组件”的方法,只有在路由匹配时才会呈现它们? 或者更好的方法来做这种事情,如果那不是反应路由器4/5如何工作。

这是一个链接到我试图解决这个问题的stackblitz

https://stackblitz.com/edit/react-jvsdsn?file=index.js

你可以做这样的事情

<Route
  path="/container1"
  render={(routeProps) => (
    <Container>
      <Page1 {...routeProps} />
    </Container>
  )}
/>
<Route
  path="/container2"
  render={(routeProps) => (
    <Container2>
      <Page1 {...routeProps} />
    </Container2>
  )}
/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM