官网:https://reactrouter.com/en/main
pnpm i react-router-dom
在文件index.ts
中用BrowserRouter
包裹整个应用,它其实是一个react context
。
import React from "react"
import ReactDOM from "react-dom/client"
import { BrowserRouter } from "react-router-dom"
import App from "./App"
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
)
在 pages 创建几个占位的页面,如About.tsx
,Book.tsx
,Home.tsx
,Context.tsx
,NewBook.tsx
,NotFood.tsx
。
为了在这些页面中设置路由,在App
组件中使用 react-router 的Routes
组件。在Routes
组件内,我们使用Route
组件来通过 path 来定义单个的路由。
Routes: A container for a nested tree of elements that renders the branch that best matches the current location.
Route: Declares an element that should be rendered at a certain URL path.
import { Route, Routes } from "react-router-dom"
import Home from "./pages/Home"
function App() {
return (
<Routes>
{/* 如果在根路径就渲染Home组件 */}
<Route path="/" element={<Home />} />
</Routes>
)
}
export default App
接着,我们完成其他的占位的页面组件对应的路由。