- 写路由配置文件
import About from "@/views/about"
import Home from "@/views/home"
import { Navigate } from "react-router-dom"
const routes = [
{
path: "/",
element: <Navigate to="/home" />
},
{
path: "/home",
element: <Home />
},
{
path: "/about",
element: <About />
},
]
export default routes
- 在顶级组件中引入路由配置,然后使用 react-router-dom 中的 useRoutes 将配置项传进去, 通过 {outlet} 形式进行路由展位
import { useState } from 'react'
import { Button } from 'antd'
import { useRoutes, Link } from 'react-router-dom'
import router from './router'
function App() {
const [count, setCount] = useState(0)
const outlet = useRoutes(router)
return (
<div className="App">
{}
<Link to="/home">home</Link>
<Link to="/about">about</Link>
{outlet}
</div>
)
}
export default App
- 在mian.tsx中 使用BrowserRouter进行包裹
import React from 'react'
import ReactDOM from 'react-dom/client'
import 'reset-css'
import '@/assets/styles/global.scss'
import App from './App'
import { BrowserRouter } from 'react-router-dom'
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
)