reactjs - 如何使用反应路由器在整个应用程序中应用某些布局?
问题描述
正如标题所说,我想在整个应用程序中实现某种布局,但该布局应该在每条路线上都保持不变。这就是我的路线的实施方式:
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,我想在整个应用程序中使用的布局。现在,我手动将此组件导入到我想要拥有此布局的所有其他组件中。如果有人知道任何方式,我可以只在一个地方拥有这个布局,然后动态更改这些道具,例如标题等,使其适合需要这个布局的组件。
解决方案
您只需要像这样在父组件中添加布局,它将应用于您的每个页面
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>
);
}
推荐阅读
- java - 关于 BigDecimal ROUND_DOWN 的问题
- reactjs - 在 React JS 的其他组件中使用状态
- python - Tkinter 和 matplotlib:绑定到 FigureCanvasTkAgg 以提取图中的光标位置?
- java - 找到 302 状态代码时,私有 IP 在 HTML 中公开
- user-interface - 缩写 UUID
- c++ - 使用模板实现派生类
- c# - Swagger API 未指示返回类型
- python-3.x - 使用 ascii 表创建函数
- python - 警告:锁定文件不是最新的 pyproject.toml 中的最新更改
- jquery - 我想在移动设备上将 zuck.js 故事项目的宽度设置为最大 320px