如何在两个不同的组件中使用路由 - ReactJS

How to use routes in two different components - ReactJS

我正在使用 ReactJS 创建一个应用程序。我正在使用来自 react-router-dom.

的反应路由器 v4

我在 index.js 文件中写了路由。

<BrowserRouter>
<Switch>
    <Route exact path="/" component={Login} />
    <Route exact path='/dashboard' component={Viewport} />
</Switch>
</BrowserRouter>

Viewport.js 文件中的其余应用程序。

    return (
        <div className="">
            <Sidebar navigation={this.viewport} />
            <HeaderBanner user={this.props.user} />
            <div className="center-panel">
                //todo
                //Can I use router here?
            </div>
        </div>
    )

用户登录后,我默认渲染包含边栏和 header 栏的视口。基于侧边栏导航中的项目点击,我需要动态渲染组件。截至目前,如果我在待办事项的地方写任何东西,它只会为完整的浏览器呈现该组件 window。 有没有办法在应用程序的多个地方使用路由器?如果是,我该如何实施?如果不是,最好的解决方案是什么? 据我所知,路由器将在应用程序中堆叠在一个地方。

提前致谢。

是的,您可以在任意多个地方使用 <Routes><Router> 组件是您只能使用一次的组件。

我最近在 youtube 上关注了一个非常有用的教程

所以我采取了一些并将其应用到您的设置中

<BrowserRouter>
  <div>
    <Route exact path="/" component={Login} />
    <Route exact path='/dashboard' component={Viewport} />
  </div>
</BrowserRouter>


import { NavLink, Route } from 'react-router-dom';

class Viewport extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <div className="Side-bar">
          <NavLink
            activeClassName="active"
            to={`${this.props.match.url}/sub-page-name-1`}>Sub Page 1</NavLink>
          <NavLink
            activeClassName="active"
            to={`${this.props.match.url}/sub-page-name-2`}>Sub Page 2</NavLink>
          <NavLink
            activeClassName="active"
            to={`${this.props.match.url}/sub-page-name-3`}>Sub Page 3</NavLink>
        </div>
        <HeaderBanner user={this.props.user} />
        <div className="center-panel">
          <Route path={`${this.props.match.url}/sub-page-name-1`} component={SubPagePanel1} />
          <Route path={`${this.props.match.url}/sub-page-name-2`} component={SubPagePanel2} />
          <Route path={`${this.props.match.url}/sub-page-name-3`} component={SubPagePanel3} />
        </div>
      </div>
    )
  }
}

我也删除了 Switch,因为我没有将它用于我的子页面...:-S

Update: Have created a repo showing a working example of sub page content

https://github.com/PocketNinjaDesign/so-sub-routes-answer