安装
npm i react-router-dom
引入
import {Route,createBrowserRouter,createRoutesFromElements,RouterProvider} from 'react-router-dom'
在app.jsx
const router = createBrowserRouter(createRoutesFromElements(<Route index element = {<h1>My App</h1>}/>)
)const App = () => {return <RouterProvider router={router}/>
}
使用object写路由
const router = createBrowserRouter([{path:"/",element:(<h2>hello rainbow</h2>)},{path:"about",element:<h2>little puppy</h2>}
])
或直接使用<Route/>组件写路由
const router = createBrowserRouter(createRoutesFromElements(<Route path='/' element={<h2>hello rainbow</h2>}></Route>
))
路由嵌套
const router = createBrowserRouter(createRoutesFromElements(<Route path='/' element={<MainLayout/>}><Route path="contact" element = {<h5 >some peopel just bad</h5>}/></Route>
))
别忘了放子路由出口
在父 route 元素中使用outlet来渲染其子 route 元素。这允许在渲染子路由时显示嵌套 UI。