在 react router 的帮助下,在 react 中创建多页面应用程序非常简单。 react router 是一个功能强大的库,允许您在 react 应用程序中实现路由。在本文中,我们将逐步介绍使用 react router 设置多页面应用程序的步骤,涵盖基本概念和代码示例以帮助您入门。
什么是 react 路由器?
react router 是一个在 react 应用程序中启用动态路由的库。它可以帮助您管理导航并根据 url 路径呈现不同的组件。使用 react router,您可以在单页面应用程序中创建无缝的多页面体验。
入门
1.安装react路由器
首先,你需要安装react router。打开终端并运行以下命令:
|
1
|
npm install react-router-dom
|
2. 设置项目结构
创建一个基本的 react 项目(如果您还没有的话)。您的项目文件夹可能如下所示:
|
1
2
3
4
5
6
7
8
9
10
11
|
my-app/
├── public/
├── src/
│ ├── components/
│ │ ├── home.JS
│ │ ├── about.js
│ │ └── contact.js
│ ├── app.js
│ ├── index.js
│ └── app.CSS
└── package.JSON
|
3.为每个页面创建组件
为应用程序的每个页面创建组件。对于此示例,我们将在组件文件夹中创建 home.js、about.js 和 contact.js。
home.js
|
1
2
3
4
5
6
7
|
import react from 'react';
function home() {
return <h1>home page</h1>;
}
export default home;
|
关于.js
|
1
2
3
4
5
6
7
|
import react from 'react';
function about() {
return <h1>about page</h1>;
}
export default about;
|
contact.js
|
1
2
3
4
5
6
7
|
import react from 'react';
function contact() {
return <h1>contact page</h1>;
}
export default contact;
|
4. 在 app.js 中设置路由
现在,在 app.js 文件中配置路由。从react-router-dom导入必要的组件并设置你的路由。
app.js
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import react from 'react';
import { browserrouter as router, route, routes, link } from 'react-router-dom';
import home from './components/home';
import about from './components/about';
import contact from './components/contact';
function app() {
return (
<router><nav><ul>
<li>
<link to="/">home</li>
<li>
<link to="/about">about</li>
<li>
<link to="/contact">contact</li>
</ul></nav><routes><route path="/" element="{<home"></route>} />
<route path="/about" element="{<about"></route>} />
<route path="/contact" element="{<contact"></route>} />
</routes></router>
);
}
export default app;
|
在此代码中:
- browserrouter(别名为 router)用于处理路由。
- 路由定义了要渲染的路径和组件。
- routes 封装了多个 route 组件。
- link 用于创建导航链接。
5.添加一些基本样式
你可以在你的app.css中添加一些基本的样式,让导航看起来更好
app.css
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
nav {
background-color: #333;
padding: 10px;
}
nav ul {
list-style: none;
padding: 0;
}
nav ul li {
display: inline;
margin-right: 10px;
}
nav ul li a {
color: white;
text-decoration: none;
}
nav ul li a:hover {
text-decoration: underline;
}
|
6. 运行您的应用程序
最后,使用以下命令运行你的 react 应用程序:
打开浏览器并导航到 HTTP://localhost:3000。您应该会看到带有有效导航链接的多页面应用程序。
结论
使用 react router,构建多页面应用程序变得轻而易举。您已经学习了如何设置基本路由、创建页面组件和管理导航。 react router 的灵活性和易用性使其成为 react 开发人员的必备工具,使您能够构建动态且用户友好的 Web 应用程序。