在布局中反应路由器4和路径参数

时间:2018-06-14 14:29:09

标签: reactjs react-router-v4

我无法理解如何通过布局组件中的React Router 4访问路径参数。

系统包含用于管理项目的页面,这些页面可在包含项目ID的路径中访问,例如/projects/1/projects/2等。 还有其他非项目页面使用相同的布局,例如/settings

如果选择了项目,布局会在页面顶部呈现一个导航栏,该导航栏应包含项目菜单。即项目菜单应显示在/projects/:projectId,而不是/settings

这是我尝试实现的简化版本: https://codesandbox.io/s/18vm42n417

任何帮助表示赞赏!

这是codesandbox.io链接中的代码:

import React from 'react'
import { render } from 'react-dom'
import { BrowserRouter, Route, Switch, Link } from 'react-router-dom'

const ProjectMenu = () => (
  <div>
    Project menu<br />
    <small>(should only be visible on project pages)</small>
  </div>
)

const NavBar = () => (
  <div style={{
    backgroundColor: 'deepPink',
    padding: 32
  }}>
    {/*
      How can I check for the projectId path param here
      and render the project menu only if it is set?
      Note that the /settings page should not have
      the project menu.
    */}
    <ProjectMenu />
  </div>
)

const Layout = ({ children }) => (
  <div style={{
    backgroundColor: 'hotPink',
  }}>
    <NavBar />
    <div style={{
      padding: 64
    }}>
      {children}
    </div>
  </div>
)

const Start = () => (
  <div>
    <Link to='/projects/1'>Project 1</Link><br />
    <Link to='/projects/2'>Project 2</Link><br />
    <Link to='/settings'>Settings</Link>
  </div>
)

const Project = ({match}) => (
  <div>
    Project {match.params.projectId}<br /><br />
    <Link to='/'>Back</Link>
  </div>
)

const Settings = () => (
  <div>
    Settings<br /><br />
    <Link to='/'>Back</Link>
  </div>
)

const App = () => (
  <BrowserRouter>
    <Layout style={{ padding: 64 }}>
      <Switch>
        <Route path='/projects/:projectId' component={Project} />
        <Route path='/settings' component={Settings} />
        <Route path='/' component={Start} />
      </Switch>
    </Layout>
  </BrowserRouter>
)

render(
  <App />,
  document.getElementById('root')
)

1 个答案:

答案 0 :(得分:0)

这是你想做的吗?

 const NavBar = () => (
      <div style={{
        backgroundColor: 'deepPink',
        padding: 32
      }}>
        {/*
          How can I check for the projectId path param here
          and render the project menu only if it is set?
          Note that the /settings page should not have
          the project menu.
        */}
        <Route path='/projects/:projectId' component={ProjectMenu} />
      </div>
    )

您可以通过这种方式接收projectID。

const ProjectMenu = ({ match }) => (
  <div>
    Project menu<br />
    <small>(should only be visible on project pages)</small>
    {match.params.projectId}
  </div>
);