react-router6.x路由配置及导航详解
作者:明知山_
这篇文章主要介绍了react-router6.x路由配置及导航,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
react-router6.x路由配置及导航
项目使用Vite
进行搭建
项目目录
安装
npm install react-router-dom
router/index.jsx
import Index from '@/pages/Index.jsx' import Home from '@/pages/Home/Home.jsx' import HomeLeft from '@/pages/Home/Home-left.jsx' import HomeRight from '@/pages/Home/Home-right.jsx' export default [ { path: "/", element: <Index />, }, { path: "/home", element: <Home />, children: [ { index: true, element: <HomeLeft /> }, { path: '/home/home-right', element: <HomeRight />, }] }, { path: "*", element: <Index /> }, ]
App.jsx
import './App.less' import React from 'react' import { useRoutes } from "react-router-dom" import router from "@/router" function App() { const element = useRoutes(router) return ( <div id='App'> {element} </div > ) } export default App
main.jsx
import React from 'react' import ReactDOM from 'react-dom' import { BrowserRouter } from "react-router-dom" import App from './App' ReactDOM.render( <BrowserRouter> <App /> </BrowserRouter>, document.getElementById('root') )
如果是嵌套路由需要加上<Outlet />
标签
Home.jsx
import React from 'react' import { Outlet, Link } from "react-router-dom" export default () => { return ( <div> <Link to="/home">左</Link> <Link to="/home/home-right">右</Link> <Outlet /> </div> ) }
路由导航
携带一个参数id=1到home
页
import { Link, useNavigate } from "react-router-dom" export default () => { let navigate = useNavigate() return ( <div> <Link to="/home?id=1">a标签跳转</Link> <button onClick={() => navigate("/home?id=1")}>编程式跳转</button> </div> ) }
通过useSearchParams
可以获取链接上的id
import React from 'react' import { Outlet, Link, useNavigate, useSearchParams } from "react-router-dom" export default () => { let navigate = useNavigate() let [searchParams] = useSearchParams() console.log(searchParams.get("id")) //1 return ( <div> <button onClick={() => navigate(-1)}>后退</button> <br /> <Link to="/home">左</Link> <Link to="/home/home-right">右</Link> <Outlet /> </div> ) }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。