想要通过react-router-dom实现类似vue的router-view的嵌套路由效果,在点击导航菜单时切换页面,官方文档是真的没找到相关内容,现做个总结:
- 在createBrowserRouter的配置中配置给目标路由配置子路由;
- 在目标组件的相应位置添加一个<Outlet />作为子路由的组件渲染容器(Outlet组件类似vue的router-view);
- 在点击menu时通过useNavigate实现路由跳转。
// router.jsx
import { Router, RouterProvider, createBrowserRouter, Route } from 'react-router-dom';
import Index from "../pages/Index";
import Login from '../pages/Login';
import Admin from '../pages/admin/index';
import Resource from '../pages/admin/Resource';
// 路由
export default function Routes () {
const router = createBrowserRouter([
{
path: '/',
element: <Index />
},
{
path: '/login',
element: <Login />
},
{
path: '/admin',
element: <Admin />,
children: [
{
path: "*",
element: <div>404</div>
},
{
path: "",
element: <div>admin index</div>
},
{
path: 'Resource',
element: <Resource />
}
]
}
]);
return (
<RouterProvider router={ router } />
)
};
// admin.jsx
const navigator = useNavigate();
const switchPage = (key) => {
setSelectedKey(key);
navigator(key);
};
另外:“*”path可以处理为匹配的的路由,用了自定义404页面
标签:dom,admin,import,element,react,path,router,路由 From: https://www.cnblogs.com/facingscreen/p/18432845