安装插件

  1. npm i react-router-dom

定义路由

  1. import Home from '../views/home'
  2. import Invoices from '../views/Invoices'
  3. import Invoice from '../views/Invoices/Invoice/Invoice.jsx'
  4. import SentInvoices from '../views/SentInvoices'
  5. import {useRoutes,BrowserRouter,Router,Roure} from 'react-router-dom'
  6. function Routers() {
  7. let element = useRoutes([
  8. // 一级路由
  9. { path: '/', element: <Home /> },
  10. { path: 'invoices',
  11. element: <Invoices />,
  12. // 二级路由 children
  13. children: [
  14. { path: ':id', element: <Invoice /> },
  15. // index : true 设置为默认路由 /invoices 下默认显示当前内容
  16. { index:true , element: <SentInvoices /> } // path: 'sent' 二级路由path不带/ /invoices/sent
  17. ]
  18. },
  19. // 重定向
  20. { path: 'home', redirectTo: '/' },
  21. // 404找不到
  22. { path: '*', element: <NotFound /> }
  23. ])
  24. return element ;
  25. }
  26. export default Routers;

注册路由

  1. import './App.css';
  2. // 引入定义好的路由规则
  3. import Routers from './router'
  4. import { BrowserRouter as Router, Link } from 'react-router-dom'
  5. function App() {
  6. return (
  7. <div className="App">
  8. <Router>
  9. <ul>
  10. {/* link 会渲染为a标签 to 代表路由要指向的页面 */}
  11. <li><Link to="/">首页</Link></li>
  12. <li><Link to="/invoices">用户管理</Link></li>
  13. <li><Link to="/invoices/1">关于</Link></li>
  14. </ul>
  15. {/* 在 BrowserRouter 的内部 使用路由规则*/}
  16. <Routers />
  17. </Router>
  18. </div>
  19. );
  20. }
  21. export default App;

二级路由出口设置

上文字 <Invoices />组件下存在下一级的路由

  1. // 导入二级路由的出口
  2. import { Outlet } from 'react-router-dom'
  3. function Invoices() {
  4. return ( <div className="">
  5. Invoices
  6. {/* 设置出口位置 */}
  7. <Outlet/>
  8. </div> );
  9. }
  10. export default Invoices;

编程式跳转

  1. // 导入模块
  2. import {useNavigate} from 'react-router-dom';
  3. function SentInvoices() {
  4. // 调用得到navgate对象
  5. const navgate = useNavigate()
  6. const handleclick = ()=>{
  7. // 路由跳转
  8. navgate('/')
  9. }
  10. return ( <div>
  11. SentInvoices+
  12. <button onClick={handleclick}>asa</button>
  13. </div> );
  14. }
  15. export default SentInvoices;