繁体   English   中英

如何使用react-router导航具有多个页面的组件

[英]How to use react-router to navigate component with multiple pages

假设我有2页和几个组件。 第一页是登录页面,另一页是主菜单。 登录页面仅包含1个组件。 用户登录到网站后,我希望react-router导航到主菜单,该主菜单下方即具有导航栏和一些组件。 我希望它能够导航到每个组件并将导航栏始终保持在顶部,即使URL已更改。

这是我尝试过的代码

// Inside the root component
<BrowserRouter>
     <Route path="/menu" component={MenuForm}/>
     <Route path="/login" component={LoginForm}/>
</BrowserRouter>

//Inside the menu page component  
<Navbar/>
<Route path="/shop" component={Shop}/>
<Route path="/categories" component={Categories}/>

使用此代码,我只能导航至菜单页面和登录页面,但无法导航至作为主菜单的子组件的商店和类别

您需要主页

<Route path="/home" component={Home}/> // all your menu and everything here

现在,如果您想在家中进入菜单,您可以像这样

<Route path="/home/menu" component={Menu}/>

此组件将在您设置嵌套路线的主页中呈现,因此匹配的路线组件将呈现

<Route path="/home/menu" component={menu}/>
<Route path="/home/profile" component={Profile}/>

我想您应该考虑创建容器组件。 第一个容器将包含您的登录路由,即“身份验证容器”,其他组件应包含在应用程序路由中,即“应用程序容器”。 您可以拥有自己的包装器。

const AppRoutes = () => {
    return (
        <>
            <Navigation scrolling={scrolling} />
            <Switch>
                <ProtectedRoute exact path="/profile" component={UserProfile} />
                <ProtectedRoute exact path="/my-orders" component={MyOrders} />
                <ProtectedRoute path="/my-saved-result" component={SavedResults} />
            </Switch>
        </>
    )
}

如果您使用react-router v4 ,则可以通过Switch组件以声明方式定义路由,如下所示:

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

const MenuForm = () => (
  <div className="app-routes">
    <NavBar />
    <Switch>
    <Route exact path="/menu">
      <Redirect to="/menu/shop" />
      </Route>
      <Route path="/menu/shop" component={Shop} />
      <Route path="/menu/categories" component={Categories} />
    </Switch>
  </div>
);

我正在这样使用

    <div className="main-panel">
        <Navbar />
        <div className="content" style={{ backgroundColor: '#f4f3ef' }}>
            <Switch>
                <Route path="/" exact component={Home} />
                <Route path="/reports" component={ReportMain} />
                <Route path="/showWebService" component={ShowWebService} />
            </Switch>
        </div>         
    </div>

导航栏链接到导航栏时,它是静态的,仅使这些组件呈现。

<Link to="/reports">
  <p>Reports</p>
</Link>

使用链接调用组件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM