首页 > 解决方案 > 如何使用反应路由器在整个应用程序中应用某些布局?

问题描述

正如标题所说,我想在整个应用程序中实现某种布局,但该布局应该在每条路线上都保持不变。这就是我的路线的实施方式:

const routes = [
  {
    path: "/",
    component: "",
    exact: true,
  },
  {
    path: "/messagelist",
    component: "",
    exact: true,
  },
  {
    path: "/ceostats",
    component: "",
    exact: true,
  },
  {
    path: "/categories",
    component: "",
    exact: true,
  },
  {
    path: "/ubcategories",
    component: "",
    exact: true,
  },
  {
    path: "/resources",
    component: "",
    exact: true,
  },
  {
    path: "/surveys",
    component: "",
    exact: true,
  },
  {
    path: "/users",
    component: Users,
    exact: true,
  },
  {
    path: "/usergroups",
    component: "",
    exact: true,
  },
  {
    path: "/users/new",
    component: User,
    exact: true,
  },
  {
    path: "/users/:id",
    component: User,
    exact: true,
  },
];

这是我存储所有路由的 Route.js 组件。

function RouterProvider() {
  return (
    <Switch>
      {routes.map((route, index) => (
        <Route
          path={route.path}
          component={route.component}
          exact={route.exact}
          key={index}
        />
      ))}
    </Switch>
  );
}

这是 RouteProvider.js,这是我进行路由的地方。

const Layout = ({ title, hasSearchBox, children, searchValue, onChange }) => {
  return (
    <LayoutContainer>
      <TopLayoutContainer>
        <Title>{title}</Title>
        {hasSearchBox ? (
          <Searchbox value={searchValue} onChange={onChange} />
        ) : (
          ""
        )}
      </TopLayoutContainer>
      {children}
    </LayoutContainer>
  );
};

这就是 Layout.js,我想在整个应用程序中使用的布局。现在,我手动将此组件导入到我想要拥有此布局的所有其他组件中。如果有人知道任何方式,我可以只在一个地方拥有这个布局,然后动态更改这些道具,例如标题等,使其适合需要这个布局的组件。

标签: reactjsreact-router

解决方案


您只需要像这样在父组件中添加布局,它将应用于您的每个页面

import { useLocation } from 'react-router-dom';

function RouterProvider() {
  let location = useLocation();
  console.log(location.pathname);
  return (
   <MyLayout>
    <Switch>
      {routes.map((route, index) => (
        <Route
          path={route.path}
          component={route.component}
          exact={route.exact}
          key={index}
        />
      ))}
    </Switch>
  </MyLayout>
  );
}

推荐阅读