官方文档:https://reactrouter.com/en/main/start/overview#pending-navigation-ui
一:简单版本
先 npm i react-router-dom
main.ts中内容替换为
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'
import {createBrowserRouter,RouterProvider,Route,Link,
} from "react-router-dom";const router = createBrowserRouter([{path: "/",element: (<div><h1>Hello World</h1><Link to="about">About Us</Link></div>),},{path: "about",element: <div>About</div>,},
]);ReactDOM.createRoot(document.getElementById('root')!).render(// <React.StrictMode>// <App />// </React.StrictMode>,<RouterProvider router={router} />
)
方式二:
// 页面、编程式跳转
main.ts
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import Page1 from './pages/page1.tsx'
import Page2 from './pages/page2.tsx'
import './index.css'
import {createBrowserRouter,RouterProvider,Route,Link,
} from "react-router-dom";const router = createBrowserRouter([{path: "/",element: <Page1 />,},{path: "about",element: <Page2 />,},
]);ReactDOM.createRoot(document.getElementById('root')!).render(// <React.StrictMode>// <App />// </React.StrictMode>,<RouterProvider router={router} />
)
page1.tsx
import { useNavigate } from 'react-router-dom'const page1 = () => {const naviagte = useNavigate()return <div>page1<button onClick={() => {naviagte('/about')}}>去page2</button></div>
}export default page1
page2.tsx
const page2 = () => {return <div>page2</div>
}export default page2