react 路由使用详情
时间: 2023-11-15 17:48:16 浏览: 42
React Router 是 React 官方提供的一个路由库,用于构建单页面应用程序(SPA)。下面是 React Router 的基本用法:
1. 安装 React Router
使用 npm 安装 React Router:
```
npm install react-router-dom
```
2. 引入 React Router
在你的组件中引入 React Router:
```
import {BrowserRouter as Router, Route, Switch, Link} from "react-router-dom";
```
3. 创建路由
在 `Router` 标签中创建路由:
```
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/contact">
<Contact />
</Route>
</Switch>
</div>
</Router>
```
在上面的代码中,我们创建了三个路由:`/`、`/about` 和 `/contact`。当用户点击对应的链接时,React Router 会渲染对应的组件。
4. 创建组件
我们需要创建三个组件:`Home`、`About` 和 `Contact`。
```
function Home() {
return <h2>Home</h2>;
}
function About() {
return <h2>About</h2>;
}
function Contact() {
return <h2>Contact</h2>;
}
```
现在,我们已经完成了一个简单的路由配置。当用户访问 `/`、`/about` 和 `/contact` 时,React Router 会渲染对应的组件。
如果你想要更加深入地了解 React Router,可以查看官方文档:https://reactrouter.com/web/guides/quick-start
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)