react及相关版本:
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router": "^6.4.2",
"react-router-dom": "^6.4.2"
实现嵌套路由:
目录结构:
main.jsx
import React from 'react' import ReactDOM from 'react-dom/client' import App from './App' import { BrowserRouter } from 'react-router-dom'; ReactDOM.createRoot(document.getElementById('root')).render( <BrowserRouter> <App /> </BrowserRouter> )
App.jsx
import { useRoutes } from 'react-router-dom'; import { routes } from './router'; function App() { return ( <div className="App"> {useRoutes(routes)} </div> ) } export default App
router/index.jsx
import Login from '../pages/login/index'; import Register from '../pages/register/index'; import Main from '../pages/main/index'; import Home from '../pages/home/index'; import Invite from '../pages/invite/index'; import NotFound from '../pages/not-found/index'; export const routes = [ { path: '/login', element: <Login />, }, { path: '/register', element: <Register />, }, { // 子路由添加 * 号 path: '/main/*', element: <Main />, // 定义二级路由,注意不要加 / children: [ { path: 'home', element: <Home />, }, { path: 'invite', element: <Invite />, }, { path:'*', element:<NotFound/> } ], }, { path:'*', element:<NotFound/> } ]
效果:
标签:index,dom,import,react,v6,path,router From: https://www.cnblogs.com/zion0707/p/16810861.html