要理解什么是 React-Router 就要先理解什么是 SPA (Single Page Application),也就是俗称的单页应用。
每个单页应用其实是一系列的 JS 文件,当用户请求网站时,网站返回一整个(或一系列)的 js 文件和 HTML,而当用户在某个页面内点击时,你需要告诉浏览器怎么加载另一个页面地址。单页应用中通常只有一个 index.html
文件的,所以浏览器自带的 <a>
链接 tag 并不能用来做单页应用的跳转,因此你需要一个在 React 中的路由实现。
然而 React 框架本身是不带路由功能的,因此如果你需要实现路由功能让用户可以在多个单页应用中跳转的话,就需要使用 React-Router。
依赖
{ "name": "basic", "private": true, "scripts": { "dev": "vite", "build": "tsc && vite build", "serve": "vite preview" }, "dependencies": { "react": "^18.2.0", "react-dom": "^18.2.0", "react-router-dom": "^6.4.0" }, "devDependencies": { "@rollup/plugin-replace": "^2.2.1", "@types/node": "14.x", "@types/react": "^18.0.15", "@types/react-dom": "^18.0.6", "@vitejs/plugin-react": "^1.0.1", "typescript": "^4.3.5", "vite": "^2.5.0" } }
代码
import * as React from 'react'; import { Routes, Route, Outlet, Link } from 'react-router-dom'; export default function App() { return ( <div> <h1>Basic Example</h1> <p> This example demonstrates some of the core features of React Router including nested <code><Route></code>s,{' '} <code><Outlet></code>s, <code><Link></code>s, and using a "*" route (aka "splat route") to render a "not found" page when someone visits an unrecognized URL. </p> {/* Routes nest inside one another. Nested route paths build upon parent route paths, and nested route elements render inside parent route elements. See the note about <Outlet> below. */} <Routes> <Route path="/" element={<Layout />}> <Route index element={<Home />} /> <Route path="about" element={<About />} /> <Route path="dashboard" element={<Dashboard />} /> {/* Using path="*"" means "match anything", so this route acts like a catch-all for URLs that we don't have explicit routes for. */} <Route path="*" element={<NoMatch />} /> </Route> </Routes> </div> ); } function Layout() { return ( <div> {/* A "layout route" is a good place to put markup you want to share across all the pages on your site, like navigation. */} <nav> <ul> <li> <Link to="/">Home1</Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/dashboard">Dashboard</Link> </li> <li> <Link to="/nothing-here">Nothing Here</Link> </li> </ul> </nav> <hr /> {/* An <Outlet> renders whatever child route is currently active, so you can think about this <Outlet> as a placeholder for the child routes we defined above. */} <Outlet /> </div> ); } function Home() { return ( <div> <h2>Home</h2> </div> ); } function About() { return ( <div> <h2>About</h2> </div> ); } function Dashboard() { return ( <div> <h2>Dashboard</h2> </div> ); } function NoMatch() { return ( <div> <h2>Nothing to see here!</h2> <p> <Link to="/">Go to the home page</Link> </p> </div> ); }
效果