就像标题所说的,我想在整个应用中实现一个特定的布局,但这个布局应该在每个路由中都存在。我的路由是这样实现的:
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>
);
}