如何为不同的 reactjs 页面显示不同的导航栏组件 [英] How to display different navbar component for different reactjs pages
问题描述
我正在尝试显示两种不同的导航栏组件,一种作为主站点导航栏,另一种用于仪表板导航栏.
I am trying to display two different navbar component one as the main site navbar and one for the dashboard navbar.
我尝试创建两个可重用的组件,即:
I have tried creating two reusable components namely:
和
这是他们的实现:
const LayoutNav = ({children}) => {
return (
<>
<section className="container-fluid">
<Navbar />
{children}
</section>
</>
);
}
对于 LayoutDashboardNav
也是一样的,我只是将
改为
下面是我的路线实施:
it is the same for LayoutDashboardNav
i only changed <Navbar />
to <DashboardNav />
below is my route implementation:
<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/>
仅在作为它们使用的组件的子页面的那些页面上.但是一切都只显示
.
I expect to see <Navbar />
or <DashboardNav />
only on those pages that are children of the components they are used in. But everything is showing only <Navbar />
.
推荐答案
你可以像这样使用高阶组件来包裹
组件.我们可以让包装器组件有一些逻辑来根据 layout
属性确定使用哪个布局.
You can use a a higher order component to wrap the <Route>
component like this. We can have the wrapper component to have some logic to determine which layout to use based on layout
prop.
// wrapper component
const DynamicLayoutRoute = props => {
const { component: RoutedComponent, layout, ...rest } = 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>
)
}
}
};
而不是做正常的<路由精确路径="/selectseat";组件={PickSeat}/>
现在你可以做<DynamicLayoutRoute 精确路径=/selectseat";组件={PickSeat} 布局=DASH_BOARD_NAV";/>
这篇关于如何为不同的 reactjs 页面显示不同的导航栏组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!