React Router 为所有路由显示一个组件(一个标题) [英] React Router display one component for all routes ( a header)

查看:99
本文介绍了React Router 为所有路由显示一个组件(一个标题)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个关于反应路由器的问题.

我有一个标题项目,我想为所有路线显示.当然,我希望这是其中的一部分,以便用户可以从导航中单击项目.

目前我的 <Header/> 在我的 <Router> 之外,我想这不起作用,因为我的路由器不知道重新渲染?

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'<div><标题/><路由器><开关><路由精确路径="/" component={Posts}/><路由精确路径="/:category/:postId" component={PostDetails}/><Route path="/:category" component={CategoryView}/></开关></路由器>

例如,我的标题有一个 <Link to="/">LOGO</Link>

解决方案

我的回答:

class App 扩展组件 {使成为() {返回 (<浏览器路由器><div><标题/><开关><路由精确路径="/" component={Posts}/><路由精确路径="/:category/:postId" component={PostDetails}/><Route path="/:category" 组件={CategoryView}/</开关><页脚/>

</BrowserRouter>);}}

Have a question regarding react router.

I have a header item that I would like to display for all routes. And of course, I want this to be part of the so that the user can click items from a nav.

Currently I have my <Header /> outside of my <Router> and I guess this isn´t working since my router then don't know to re-render?

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
  <div>
    <Header />
    <Router>
      <Switch>
        <Route exact path="/" component={Posts} />
        <Route exact path="/:category/:postId" component={PostDetails} />
        <Route path="/:category" component={CategoryView} />
      </Switch>
    </Router>
  </div>

And my header has for example a <Link to="/">LOGO</Link>

解决方案

My comment in answer:

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <div> 
          <Header />
          <Switch>
           <Route exact path="/" component={Posts} />
           <Route exact path="/:category/:postId" component={PostDetails} />
           <Route path="/:category" component={CategoryView} /
          </Switch>
          <Footer />
        </div>
      </BrowserRouter>
    );
  }
}

这篇关于React Router 为所有路由显示一个组件(一个标题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆