1. install package

    yarn add react-router-dom
  2. in scr/App.tsx

    import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
    import MainPage from './pages/MainPage/MainPage'
    import User from './pages/User/User'
    import HomePage from './pages/HomePage/HomePage'
    export default function App() {
        return (
            <Router>
                <Routes>
              <Route path='/' element={<MainPage />}>
                <Route index element={<HomePage />} />
                <Route path='user' element={<User />} />
              </Route>
            </Routes>
            </Router>
        )
    }
  3. in src/pages/MainPage/MainPage.tsx

    import { Outlet } from "react-router-dom"
    export default function App() {
        return (
            <div>
                <div>Navigator</div>
                <Outlet context={{username: 'Tommy'}} />
            </div>
        )
    }
  4. in src/pages/User/User.tsx

    import { useOutletContext } from "react-router-dom"
    export default function App() {
        const context: any = useOutletContext()
        return (
            <div>
                <div>context.username</div>
            </div>
        )
    }

添加新评论