【React Router】快速使用

组件

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import {BrowserRouter} from "react-router-dom";

// 创建根实例
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    // history 模式
    <BrowserRouter>
        <App />
    </BrowserRouter>
);
  • BrowserRouter:整个前端路由以 history 模式开始,包裹根组件
  • HashRouter:整个前端路由以 hash 模式开始,包裹根组件
import {Navigate, NavLink, Route, Routes} from "react-router-dom";
import Home from "./components/Home";
import About from "./components/About";
import Add from "./components/Add";
import './css/App.css'

function App() {
    return (
        <div id="app" className="container">
            {/*导航栏*/}
            <nav className="navbar navbar-inverse navbar-fixed-top">
                <div className="container">
                    <div className="navbar-header">
                        <button type="button" className="navbar-toggle collapsed" data-toggle="collapse"
                                data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                            <span className="sr-only">Toggle navigation</span>
                            <span className="icon-bar"></span>
                            <span className="icon-bar"></span>
                            <span className="icon-bar"></span>
                        </button>
                        <div className="navbar-brand">学生管理系统</div>
                    </div>
                    <div id="navbar" className="collapse navbar-collapse">
                        <ul className="nav navbar-nav">
                            {/*路由跳转*/}
                            <NavLink to="/home" className="navigation">主页</NavLink>
                            <NavLink to="/about" className="navigation">关于我们</NavLink>
                        </ul>
                        <ul className="nav navbar-nav navbar-right">
                            <NavLink to="/add" className="navigation">添加用户</NavLink>
                        </ul>
                    </div>
                </div>
            </nav>
            <div style={{marginTop: 60}}>
                {/*匹配的路由显示*/}
                <Routes>
                    <Route path="/home" element={<Home/>}/>
                    <Route path="/about" element={<About/>}/>
                    <Route path="/add" element={<Add/>}/>
                    <Route path="/" element={<Navigate replace to="/home"/>}/>
                </Routes>
            </div>
        </div>
    );
}

export default App;
  • Routes:提供上下文环境

  • Route: 书写对应的路由和对应的组件

    • path:匹配的路由
    • element:匹配路由时要渲染的组件
  • Navigate:重定向,类似于 useNavigate 的返回值函数,但这个是组件

  • NavLink:和 Link 一样会被渲染为 a 标签,和 Link 的区别是他有一个名为 active 的激活样式,所以一般用于顶部或者左侧导航栏的跳转

  • Outlet:相当于 Vue Router 的 router-view;需要有嵌套 ROute 或者 useRoutes 中使用children 属性的配置,children 对应一个数组,数组里是一个个路由

function Dashboard() {
  return (
    <div>
      <h1>Dashboard</h1>

      {/* This element will render either <DashboardMessages> when the URL is
          "/messages", <DashboardTasks> at "/tasks", or null if it is "/"
      */}
      <Outlet />
    </div>
  );
}

function App() {
  return (
    <Routes>
      <Route path="/" element={<Dashboard />}>
        <Route
          path="messages"
          element={<DashboardMessages />}
        />
        <Route path="tasks" element={<DashboardTasks />} />
      </Route>
    </Routes>
  );
}

Hooks

  • useLocation:获取到 location 对象,location 对象中可以获取 state(其他路由跳转过来的时候会在state 里面传递额外的数据) 等的属性
const location = useLocation()
console.log(location.state)
  • useNavigate:
const navigate = useNavigate()
// 这里路径必须是 /home 因为如果从 / -> /home 的话,/home 页的 location 并不会传递
navigate('/home', {
    state: {
        alert: '用户添加成功',
        type: 'success'
    }
})
  • useParams:获取动态参数
<Route path="/detail/:id" element={<Detail />}/>
const {id} = useParams()
  • useRoutes:类似于 Vue Router 声明路由的方式
import * as React from "react";
import { useRoutes } from "react-router-dom";

function Router() {
  const element = useRoutes([
    {
      path: "/",
      element: <Dashboard />,
      children: [
        {
          path: "messages",
          element: <DashboardMessages />,
        },
        { path: "tasks", element: <DashboardTasks /> },
      ],
    },
    { path: "team", element: <AboutPage /> },
  ]);
  return element;
}

export default Router;
import RouterConfig from './router/router.jsx'
// ...
<RouterConfig />

相关推荐

  1. ReactRouter v6升级的步骤

    2024-04-23 13:50:04       25 阅读
  2. jmeter快速使用

    2024-04-23 13:50:04       44 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-23 13:50:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-23 13:50:04       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-23 13:50:04       82 阅读
  4. Python语言-面向对象

    2024-04-23 13:50:04       91 阅读

热门阅读

  1. spring中的Aware接口概念

    2024-04-23 13:50:04       35 阅读
  2. 8.Godot 函数|变量|运算符|条件循环语句

    2024-04-23 13:50:04       35 阅读
  3. python机器学习库中Scikit-learn和TensorFlow如何选择?

    2024-04-23 13:50:04       36 阅读
  4. 【OS】AUTOSAR架构下MCAL Modules软件分区问题分析

    2024-04-23 13:50:04       37 阅读
  5. SQL中不等于的写法

    2024-04-23 13:50:04       31 阅读
  6. Linux文件/目录高级管理一 头歌

    2024-04-23 13:50:04       38 阅读
  7. 智能合约区块应用链交易所系统教程开发搭建

    2024-04-23 13:50:04       34 阅读
  8. 笔记:Python 循环结构练习题

    2024-04-23 13:50:04       35 阅读
  9. 实验3 7段数码管译码器动态显示

    2024-04-23 13:50:04       26 阅读
  10. yolov8下实现绿萝识别

    2024-04-23 13:50:04       43 阅读
  11. 【代码随想录】day44

    2024-04-23 13:50:04       112 阅读
  12. oracle--存储过程基本框架

    2024-04-23 13:50:04       111 阅读
  13. 富格林:善用正规要领杜绝受害

    2024-04-23 13:50:04       120 阅读
  14. 嵌入式学习——C语言基础——day6

    2024-04-23 13:50:04       34 阅读
  15. 2024.4.22每日一题

    2024-04-23 13:50:04       34 阅读
  16. RedisSearch:一个基于Redis的搜索引擎模块

    2024-04-23 13:50:04       188 阅读
  17. VScode 里面使用 python 去直接调用 CUDA

    2024-04-23 13:50:04       35 阅读