仅在几条路线上渲染组件的一部分

时间:2019-06-04 12:56:22

标签: reactjs react-router

我有我的应用程序,我正在使用react-router。在每条路径上我都渲染了Navbar,在Navbar中我有输入字段,我只想在两条路径上渲染。我该怎么做 ?路由匹配后,是否可以使用“ If”来渲染组件的一部分?

2 个答案:

答案 0 :(得分:1)

在您的Route中,您将有RouteParams的集合(匹配,位置和历史记录)。您可以使用例如location.pathname有条件地呈现您想要的任何内容。

类似:

<Router>
  <Route render={({match,location,history})=>{
    const showNavFields = location.pathname==='/your-path'
    return {
     <NavBar showNavFields={showNavFields}/>  
    }
 }}/>
 <Switch>
   <Route path="/your-path" component="AComponent"/ >
   <Route path="/your-other-path" component="AnotherComponent"/ >
 </Switch>
</Router>

答案 1 :(得分:1)

我们可以为此使用match.url。

工作代码。如果路由为route matched,在这里我们在路由器URL后面附加/topics/rendering

import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

function BasicExample() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/topics">Topics</Link>
          </li>
        </ul>

        <hr />

        <Route exact path="/" component={Home} />
        <Route path="/topics" component={Topics} />
      </div>
    </Router>
  );
}

function Home() {
  return (
    <div>
      <h2>Home</h2>
    </div>
  );
}

function Topics({ match }) {
  return (
    <div>
      <h2>Topics</h2>
      <ul>
        <li>
          <Link to={`${match.url}/rendering`}>Rendering with React</Link>
        </li>
        <li>
          <Link to={`${match.url}/components`}>Components</Link>
        </li>
      </ul>

      <Route path={`${match.path}/:topicId`} component={Topic} />
      <Route
        exact
        path={match.path}
        render={() => <h3>Please select a topic.</h3>}
      />
    </div>
  );
}

function Topic({ match }) {
  if (match.url === '/topics/rendering') {
    return (
    <div>
      <h3>route matched {match.params.topicId}</h3>
    </div>
  )
  } else {
    return (
      <div>
        <h3>{match.params.topicId}</h3>
      </div>
    )

  }

}

export default BasicExample;