如何在 react-router-dom 中隐藏标头组件?

Siv*_*s N 5 reactjs react-router-v4 react-router-dom

我在这里有一个像这样的 React 应用程序我想从登录和注册等页面隐藏全局标题组件。我在互联网上的 React-Router-v4 中找不到任何方法。有人可以对我有所了解以进一步进行吗?

const App = () => (
  <Router>
    <div className="app-wrapper">
      <Header />
      <main>
        <Route path="/" exact component={Home} />
        <Route path="/login" exact component={Login} />
        <Route path="/contact" component={Contact} />
      </main>
      <footer>
        &copy; Acme Inc. 2017
      </footer>
    </div>
  </Router>
);
Run Code Online (Sandbox Code Playgroud)

Gul*_*ain 6

您可以使用withRouter高阶组件访问props.location应用程序组件中的对象,并使用以下命令检查用户是否在登录或注册页面上props.location.pathname

请记住,withRouter如果您要访问的组件props.matchprops.location对象是由<Route/>

import {Route, withRouter} from 'react-router-dom'

const App  = (props) => {
return(
  <Router>
    <div className="app-wrapper">
     {
      props.location.pathname!=='/login' ? <Header/>:null
     }
      <main>
        <Route path="/" exact component={Home} />
        <Route path="/login" exact component={Login} />
        <Route path="/contact" component={Contact} />
      </main>
      <footer>
        &copy; Acme Inc. 2017
      </footer>
    </div>
  </Router>
)
};


export default withRouter(App);
Run Code Online (Sandbox Code Playgroud)


Vor*_*can 2

如果您只是想根据授权状态隐藏/显示标题,那么您可以将包含授权状态的对象传递给 Header 组件,该组件将根据该对象呈现菜单项。

我在这里分叉了演示: https: //codesandbox.io/s/pjyl9y17rx

在这里,我只是传递一个布尔值来表示授权状态,但您已经明白了。

基于路径渲染路由的另一个选项是在路径中使用正则表达式,我相信这是受支持的,通过此对话: https ://github.com/ReactTraining/react-router/issues/391