1

我正在尝试显示两个不同的导航栏组件,一个作为主站点导航栏,一个用于仪表板导航栏。

我尝试创建两个可重用的组件,即:

<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 />

4

1 回答 1

1

您可以像这样使用更高阶的组件来包装<Route>组件。我们可以让包装器组件有一些逻辑来根据layoutprop 确定要使用的布局。

// 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>
      )
    }
  }
};

而不是做正常的 <Route exact path="/selectseat" component={PickSeat} />

现在你可以做 <DynamicLayoutRoute exact path="/selectseat" component={PickSeat} layout="DASH_BOARD_NAV" />

于 2019-09-04T14:09:49.523 回答