目录
router/index.tsx
import App from "App";
import Home from "pages/Home";
import List from "pages/List";
import Detail from "pages/Detail";
import About from "pages/About";
import Login from "pages/Login";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
const MyRouter = () => (
<Router>
<Routes>
<Route path="/" element={<App />}>
<Route index element={<Home />}></Route>
<Route path="/list/" element={<List />}></Route>
<Route path="/list/:id" element={<List />}></Route>
<Route path="/detail" element={<Detail />}></Route>
<Route path="/about" element={<About />}></Route>
</Route>
<Route path="/login" element={<Login />}></Route>
</Routes>
</Router>
);
export default MyRouter;
App.tsx
import React from "react";
import { Outlet, Link } from "react-router-dom";
function App() {
return (
<div>
<ul>
<li>
<Link to={"/list"}>列表页(不带id)</Link>
</li>
<li>
<Link to={"/list/456"}>列表页(带id)</Link>
</li>
<li>
<Link to={"/detail?id=123"}>详情页</Link>
</li>
<li>
<Link to={"/about"}>关于我们</Link>
</li>
</ul>
<Outlet />
</div>
);
}
export default App;
参数获取
1、子路由形式携带
如上面代码的点击列表页带id "/list/456" 跳转列表页
<Route path="/list/:id" element={<List />}></Route>
此时可以使用React Router Dom提供的Hook useParams 在列表页获取:
List.tsx
import React from "react";
import { useParams } from "react-router-dom";
export default function List() {
const { id } = useParams();
return (
<div>
<h1>列表 - id: {id}</h1>
<h1>yusir</h1>
</div>
);
}
2、问号(?)形式参数
<Link to={"/detail?id=123"}>详情页</Link>
点击携带参数进入详情页
此时可以使用React Router Dom提供的Hook useSearchParams 在详情页获取:
Detail.tsx
import React from "react";
import { useSearchParams } from "react-router-dom";
export default function Detail() {
const [params] = useSearchParams();
console.log(params.getAll('id')) // ['123']
let myId = params.getAll("id")[0];
return (
<div>
<h1>Detail - id: {myId}</h1>
<h1>yusir</h1>
</div>
);
}
3、事件跳转传参
事件中执行跳转页面,可以使用useNavigate这个hook进行跳转。