本文介绍了使用 React Router 进行条件渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想渲染一些顶部带有导航的路由,而渲染其他路由(如注册/登录页面)而没有任何导航.

对于导航的设置,我有:

const App = () =>(<路由器><div><导航/><div><路由精确路径="/" component={Home}/><Route path="/account" component={Account}/><Route path="/news" component={News}/>

<页脚/>

</路由器>);

我正在尝试使用 React Router 找到处理此问题的最佳方法(似乎它必须使用某种类型的条件来处理?-如果我当前的路由与这些路由中的任何一个匹配,则像这样渲染否则呈现这个.").

谢谢!

解决方案

你至少有两种可能:

  1. 使用 Route "path" 属性来测试路由并渲染组件.Path 属性接受 path.to.regexp 表达式.
  2. 使用 withRouter 方法包装您的组件,然后Nav 测试路由是否匹配,否则渲染 null.

第一个答案:

const App = () =>(<路由器><div><Route path="/(?!signin|signup)" component={Nav}/><div><路由精确路径="/" component={Home}/><Route path="/account" component={Account}/><Route path="/news" component={News}/>

<页脚/>

</路由器>);

第二个答案:

import { withRouter } from 'react-router'const NavWithRouter = withRouter(Nav);const App = () =>(<路由器><div><NavWithRouter/><div><路由精确路径="/" component={Home}/><Route path="/account" component={Account}/><Route path="/news" component={News}/>

<页脚/>

</路由器>);

I'd like to render some routes with a nav at the top, while rendering other routes (like a sign-up / sign-in page) without any nav.

For the setup with the nav, I have:

const App = () => (
  <Router>
    <div>
      <Nav />
      <div>
        <Route exact path="/" component={Home} />
        <Route path="/account" component={Account} />
        <Route path="/news" component={News} />
      </div>
      <Footer />
    </div>
  </Router>
);

I'm trying to find the best way of handling this with React Router (seems like it would have to handled with some type of conditional maybe? - "if my current route matches any one of these routes, then render like so else render this.").

Thanks!

解决方案

You have at least two possibilities:

  1. Use Route "path" property to test the route and render the component. Path property accepts path.to.regexp expressions.
  2. Wrap your component with withRouter method and inside Nav test if the route matches and render null otherwise.

First answer:

const App = () => (
  <Router>
    <div>
      <Route path="/(?!signin|signup)" component={Nav}/>
      <div>
        <Route exact path="/" component={Home} />
        <Route path="/account" component={Account} />
        <Route path="/news" component={News} />
      </div>
      <Footer />
    </div>
  </Router>
);

Second answer:

import { withRouter } from 'react-router'
const NavWithRouter = withRouter(Nav);

const App = () => (
  <Router>
    <div>
      <NavWithRouter/>
      <div>
        <Route exact path="/" component={Home} />
        <Route path="/account" component={Account} />
        <Route path="/news" component={News} />
      </div>
      <Footer />
    </div>
  </Router>
);

这篇关于使用 React Router 进行条件渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 19:13