Skip to content
索引

react-router

react-router库包含三个不同的npm包,以下每个包都有不同的用途

  • react-router
  • react-router-dom
  • react-router-native

react-router 是核心程序包,用作列出react-router-domreact-router-native 的对等依赖项

react-router-dom 是web应用路由包

react-router-native 用于开发react native应用的绑定

安装

所以正常开发web应用选择使用react-router-dom

sh
pnpm i -s react-router-dom
pnpm i -s react-router-dom

使用

tsx
import React from "react"
import { BrowserRouter, Route, Routes } from "react-router-dom"
import Register from "./pages/Register"
import Login from "./pages/Register"
import Chat from "./pages/Chat"
function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/register" element={<Register />}></Route>
        <Route path="/login" element={<Login />}></Route>
        <Route path="/" element={<Chat />}></Route>
      </Routes>
    </BrowserRouter>
  )
}

export default App
import React from "react"
import { BrowserRouter, Route, Routes } from "react-router-dom"
import Register from "./pages/Register"
import Login from "./pages/Register"
import Chat from "./pages/Chat"
function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/register" element={<Register />}></Route>
        <Route path="/login" element={<Login />}></Route>
        <Route path="/" element={<Chat />}></Route>
      </Routes>
    </BrowserRouter>
  )
}

export default App

跳转

页面跳转

tsx
import { Link } from "react-router-dom";
function Home() {
  return (
    <>
      <main>
        <h2>Welcome to the homepage!</h2>
      </main>
      <nav>
        <Link to="/about">About</Link>
      </nav>
    </>
  )
}
import { Link } from "react-router-dom";
function Home() {
  return (
    <>
      <main>
        <h2>Welcome to the homepage!</h2>
      </main>
      <nav>
        <Link to="/about">About</Link>
      </nav>
    </>
  )
}

js跳转

tsx
import { seNavigate } from "react-router-dom"
function Register() {
  const navigator = useNavigate()
  navigator("/home")
  )
}
import { seNavigate } from "react-router-dom"
function Register() {
  const navigator = useNavigate()
  navigator("/home")
  )
}

navigete默认push模式,使用replace模式需要添加 navigate("/home", { replace: true })

Released under the MIT License.