18 从零到上手学习 React 框架教程

18 从零到上手学习 React 框架教程

小节 1: 环境配置

在学习 React 之前,我们需要配置开发环境。以下是配置 React 开发环境的步骤。

1.1 安装 Node.js

在使用 React 之前,首先需要安装 Node.js。可以从 Node.js 官方网站 下载并安装最新版本。

1.2 安装 Create React App

Create React App 是一个官方提供的脚手架工具,可以快速创建 React 应用。打开终端,执行以下命令:

1
npx create-react-app my-app

这将创建一个名为 my-app 的新项目,相关依赖会自动安装。

1.3 启动开发服务器

进入创建的项目文件夹,并启动开发服务器:

1
2
cd my-app
npm start

此时,你的 React 应用应该会在浏览器中自动打开,通常是 http://localhost:3000

小节 2: 配置应用路由

为了在 React 应用中实现页面之间的跳转与路由管理,我们需要使用 react-router-dom 包。以下是配置应用路由的详细步骤。

2.1 安装 react-router-dom

首先,使用 npm 安装 react-router-dom 依赖:

1
npm install react-router-dom

2.2 创建页面组件

为了演示路由的使用,我们需要创建几个基本的页面组件。可以在 src 文件夹中创建以下文件:

  • Home.js
  • About.js
  • NotFound.js

示例 Home.js

1
2
3
4
5
6
7
8
// src/Home.js
import React from 'react';

const Home = () => {
return <h2>首页</h2>;
};

export default Home;

示例 About.js

1
2
3
4
5
6
7
8
// src/About.js
import React from 'react';

const About = () => {
return <h2>关于我们</h2>;
};

export default About;

示例 NotFound.js

1
2
3
4
5
6
7
8
// src/NotFound.js
import React from 'react';

const NotFound = () => {
return <h2>页面未找到</h2>;
};

export default NotFound;

2.3 设置路由

接下来需要在 src/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
// src/App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';
import NotFound from './NotFound';

const App = () => {
return (
<Router>
<div>
<h1>我的 React 应用</h1>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route component={NotFound} />
</Switch>
</div>
</Router>
);
};

export default App;

2.4 访问不同的路由

现在,可以在浏览器中访问不同的路由:

  • 访问 http://localhost:3000/ 将看到“首页”。
  • 访问 http://localhost:3000/about 将看到“关于我们”。
  • 访问一个不存在的页面(例如 http://localhost:3000/unknown)将看到“页面未找到”。

小节总结

在本小节中,我们完成了以下内容:

  1. 安装并配置了 react-router-dom
  2. 创建了基本的页面组件。
  3. 在应用中设置了路由,使得用户可以在不同页面间导航。

通过这些步骤,你的 React 应用现在拥有了基础的路由功能。这是构建更复杂应用的重要基础,接下来可以逐步添加更多功能与页面。

18 从零到上手学习 React 框架教程

https://zglg.work/react-tutorial/18/

作者

AI教程网

发布于

2024-08-08

更新于

2024-08-10

许可协议