自学内容网 自学内容网

react 的路由功能

1. 安装依赖

pnpm add react-router-dom

2. 基本的路由设置(BrowserRouter)

在 main.tsx 入口文件中使用`BrowserRouter`组件来包裹整个应用。它会监听浏览器的 URL 变化。

import { StrictMode } from "react";

import { createRoot } from "react-dom/client";

import { BrowserRouter } from "react-router-dom";



import App from "./App.tsx";



createRoot(document.getElementById('root')!).render(

  <BrowserRouter>

    <App />

  </BrowserRouter>

)

3. 定义路由和组件(Routes 和 Route)

在根组件 App.tsx 定义路由和对应组件。

import { Routes, Route } from "react-router-dom";

import Home from "./components/Home";

import About from "./components/About";

import Contact from "./components/Contact";



const App = () => {

  return (

    <div>

      <Routes>

        <Route path="/" element={<Home />} />

        <Route path="/about" element={<About />} />

        <Route path="/contact" element={<Contact />} />

      </Routes>

    </div>

  );

};

4. 导航链接(Link)

在不刷新整个页面的情况下改变 URL 并触发相应的路由。

import React from "react";

import { Link } from "react-router-dom";



const Home = () => {

  return (

    <div>

      <h1>Home Page</h1>

      <Link to="/about">About</Link>

      <Link to="/contact">Contact</Link>

    </div>

  );

};

5. 嵌套路由

例如:假设`About`组件内部还有子路由,如`About`组件中有`Team`和`History`两个子部分。

// App.js

import { Routes, Route } from "react-router-dom";

import Home from "./components/Home";

import About from "./components/About";

import Contact from "./components/Contact";



const App = () => {

  return (

    <div>

      <Routes>

        <Route path="/" element={<Home />} />

        <Route path="/about" element={<About />}>

          <Route path="team" element={<Team />} />

          <Route path="history" element={<History />} />

        </Route>

        <Route path="/contact" element={<Contact />} />

      </Routes>

    </div>

  );

};

然后在`About`组件中,需要使用`Outlet`组件来显示子路由对应的组件。

import React from "react";

import { Outlet } from "react-router-dom";



const About = () => {

  return (

    <div>

      <h1>About Page</h1>

      <Outlet />

    </div>

  );

};

6. 编程式导航(useNavigate)

使用`useNavigate`钩子函数。

import { useState } from "react";

import { useNavigate } from "react-router-dom";



const SomeComponent = () => {

  const navigate = useNavigate();

  const [data, setData] = useState("");



  const handleClick = () => {

    if (data === "go-to-about") {

      navigate("/about");

    }

  };



  return (

    <div>

      <input

        type="text"

        value={data}

        onChange={(e) => setData(e.target.value)}

      />

      <button onClick={handleClick}>Navigate</button>

    </div>

  );

};


原文地址:https://blog.csdn.net/weixin_64684095/article/details/144097596

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!