下载
npm install react-router-dom@6
例子
官网,我们按照官网的create-react-app来进行搭建
入口文件main.js
import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from "react-router-dom";
import App from "./App.jsx";
const root = ReactDOM.createRoot(
document.getElementById("root")
);
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
应用文件App.jsx
import { Routes, Route, Link } from "react-router-dom";
export default function App() {
return (
<div className="App">
<h1>Welcome to React Router!</h1>
<Routes>
<Route path="/" element={<Home />} />
<Route path="about" element={<About />} />
</Routes>
</div>
);
}
function Home() {
return (
<>
<main>
<h2>Welcome to the homepage!</h2>
<p>You can do this, I believe in you.</p>
</main>
<nav>
<Link to="/about">About</Link>
</nav>
</>
);
}
function About() {
return (
<>
<main>
<h2>Who are we?</h2>
<p>
That feels like an existential question, don't you
think?
</p>
</main>
<nav>
<Link to="/">Home</Link>
</nav>
</>
);
}
运行npm run dev ,那么我们就会看到效果 我们点击超链接,就会发现,可以跳转到另一个页面
|