我试图显示两个不同的导航栏组件,一个作为主站点导航栏,另一个显示为仪表板导航栏。
我尝试创建两个可重用组件,即:
<LayoutNav />
和<DashboardNav />
这是它们的实现:
const LayoutNav = ({children}) => {
return (
<>
<section className="container-fluid">
<Navbar />
{children}
</section>
</>
);
}
对于LayoutDashboardNav
来说是一样的,我只是将<Navbar />
更改为<DashboardNav />
,以下是我的路由实现:
<BrowserRouter>
<Switch>
<LayoutNav>
<Route exact path="/registervehicle" component={RegVehicle} />
<Route exact path="/result" component={SearchResults} />
<Route exact path="/selectseat" component={PickSeat} />
<Route exact path="/forgotpassword" component={ForgotPassword} />
<Route exact path="/resetpassword" component={ResetPassword} />
<Route exact path="/register" component={Registration} />
<Route exact path="/login" component={LoginAuth} />
<Route exact path="/" component={Home} />
</LayoutNav>
<LayoutDashboardNav>
<Route exact path="/companydashboard" component={CompanyDashboard} />
</LayoutDashboardNav>
<Route component={NotFound} />
</Switch>
<Footer />
</BrowserRouter>
我希望仅在这些页面所属的页面上看到<Navbar />
或<DashboardNav />
。但是所有内容仅显示<Navbar />
。
答案 0 :(得分:0)
您可以使用更高阶的组件来包装<Route>
组件,如下所示。我们可以使包装器组件具有一些逻辑,以便根据layout
属性来确定使用哪种布局。
// wrapper component
const DynamicLayoutRoute = props => {
const { component: RoutedComponent, layout, ...rest } = this.props;
// render actual Route from react-router
const actualRouteComponent = (
<Route
{...rest}
render={props => (
<RoutedComponent {...props} />
)}
/>
);
// depends on the layout, you can wrap Route component in different layouts
switch (layout) {
case 'NAV': {
return (
<LayoutNav>
{actualRouteComponent}
</LayoutNav>
)
}
case 'DASH_BOARD_NAV': {
return (
<LayoutDashboardNav>
{actualRouteComponent}
</LayoutDashboardNav>
)
}
default: {
return (
<LayoutNav>
{actualRouteComponent}
</LayoutNav>
)
}
}
return (
<Route
{...rest}
render={props => (
userContext && <RoutedComponent {...props} />
)}
/>
);
};
代替正常
<Route exact path="/selectseat" component={PickSeat} />
现在您可以做
<DynamicLayoutRoute exact path="/selectseat" component={PickSeat} layout="DASH_BOARD_NAV" />