当前位置: 首页 > news >正文

React 入门教程:构建第一个 React 应用

本教程将带你从零开始构建你的第一个 React 应用。我们将创建一个简单的计数器应用,涵盖 React 的基本概念和开发流程。

准备工作

在开始之前,请确保你的开发环境满足以下要求:

  • Node.js (建议使用最新的 LTS 版本)

  • npm 或 yarn (Node.js 安装时会自带 npm)

  • 代码编辑器 (如 VS Code)

第一步:创建 React 应用

React 官方推荐使用 create-react-app 工具来快速搭建项目:

npx create-react-app my-first-react-app
cd my-first-react-app
npm start

执行这些命令后,你的默认浏览器应该会自动打开 http://localhost:3000 并显示 React 的欢迎页面。

第二步:理解项目结构

让我们看一下 create-react-app 生成的主要文件和目录:

my-first-react-app/
├── node_modules/     # 所有依赖项
├── public/           # 静态文件
│   ├── index.html    # 主HTML文件
│   └── ...
├── src/              # React 源代码
│   ├── App.js        # 主React组件
│   ├── index.js      # 应用入口点
│   └── ...
├── package.json      # 项目配置和依赖
└── ...

第三步:创建第一个组件

让我们修改 src/App.js 来创建我们的计数器组件:

import React, { useState } from 'react';function App() {// 使用 useState Hook 来管理状态const [count, setCount] = useState(0);// 增加计数const increment = () => {setCount(count + 1);};// 减少计数const decrement = () => {setCount(count - 1);};// 重置计数const reset = () => {setCount(0);};return (<div style={{ textAlign: 'center', marginTop: '50px' }}><h1>我的第一个 React 应用</h1><h2>计数器: {count}</h2><button onClick={increment} style={{ margin: '5px' }}>增加</button><button onClick={decrement} style={{ margin: '5px' }}>减少</button><button onClick={reset} style={{ margin: '5px' }}>重置</button></div>);
}export default App;

第四步:理解代码

让我们分解一下这个简单的组件:

  1. 导入 Reactimport React, { useState } from 'react'; - 导入 React 和 useState Hook

  2. 函数组件:我们使用函数式组件而不是类组件,这是 React 的现代写法

  3. useState Hookconst [count, setCount] = useState(0); 创建了一个状态变量 count 和更新它的函数 setCount,初始值为 0

  4. 事件处理:我们定义了三个函数来处理按钮点击事件,分别用于增加、减少和重置计数器

  5. JSX:返回的 JSX 描述了 UI 的结构和外观

第五步:运行应用

确保你的开发服务器正在运行(如果没有,使用 npm start 启动它)。你应该能在浏览器中看到:

  • 一个标题 "我的第一个 React 应用"

  • 显示当前计数的文本

  • 三个按钮:增加、减少和重置

尝试点击这些按钮,观察计数器的变化。

第六步:添加样式

让我们为计数器添加一些基本样式。在 src/App.js 中,我们可以添加 CSS-in-JS 样式:

// 在 return 语句前定义样式对象
const styles = {container: {textAlign: 'center',marginTop: '50px',fontFamily: 'Arial, sans-serif'},counter: {fontSize: '48px',margin: '20px 0',color: '#333'},button: {padding: '10px 20px',fontSize: '16px',margin: '5px',cursor: 'pointer',backgroundColor: '#61dafb',border: 'none',borderRadius: '5px',color: 'white'},buttonHover: {backgroundColor: '#4fa8d3'}
};// 然后修改 JSX 部分
return (<div style={styles.container}><h1>我的第一个 React 应用</h1><h2 style={styles.counter}>计数器: {count}</h2><button onClick={increment} style={styles.button}onMouseOver={(e) => e.target.style.backgroundColor = styles.buttonHover.backgroundColor}onMouseOut={(e) => e.target.style.backgroundColor = styles.button.backgroundColor}>增加</button>{/* 其他按钮类似 */}</div>
);

第七步:组件拆分

随着应用增长,最好将组件拆分为更小的可重用部分。让我们创建一个单独的 Counter 组件:

  1. 创建 src/components/Counter.js:

    import React, { useState } from 'react';function Counter() {const [count, setCount] = useState(0);const increment = () => setCount(count + 1);const decrement = () => setCount(count - 1);const reset = () => setCount(0);return (<div style={{ textAlign: 'center', margin: '20px' }}><h2>计数器: {count}</h2><button onClick={increment}>增加</button><button onClick={decrement}>减少</button><button onClick={reset}>重置</button></div>);
    }export default Counter;
  2. 修改 src/App.js:

    import React from 'react';
    import Counter from './components/Counter';function App() {return (<div style={{ textAlign: 'center', marginTop: '50px' }}><h1>我的第一个 React 应用</h1><Counter /></div>);
    }export default App;

第八步:添加多个计数器

现在我们可以轻松地添加多个计数器实例:

function App() {return (<div style={{ textAlign: 'center', marginTop: '50px' }}><h1>我的第一个 React 应用</h1><Counter /><Counter /><Counter /></div>);
}

每个计数器都有自己独立的状态!

第九步:测试与部署

添加单元测试

React 应用通常使用 Jest 和 React Testing Library 进行测试。CRA 已经配置好了这些工具。

创建 src/components/Counter.test.js

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import Counter from './Counter';test('计数器初始值正确', () => {const { getByText } = render(<Counter initialValue={5} />);expect(getByText('当前值: 5')).toBeInTheDocument();
});test('增加按钮工作正常', () => {const { getByText } = render(<Counter />);fireEvent.click(getByText('+'));expect(getByText('当前值: 1')).toBeInTheDocument();
});

运行测试:

npm test

构建生产版本

准备部署时,运行:

npm run build

这会:

  1. 优化代码(压缩、tree-shaking 等)

  2. 生成静态文件到 build 目录

  3. 准备好部署到任何静态文件服务器

部署选项

有多种方式可以部署 React 应用:

  1. Vercel:最简单的部署平台之一

    npm install -g vercel
    vercel
  2. Netlify:拖放 build 文件夹到 Netlify

  3. GitHub Pages

    • 安装 gh-pagesnpm install gh-pages --save-dev

    • 在 package.json 中添加:

      "homepage": "https://username.github.io/repo-name",
      "scripts": {"predeploy": "npm run build","deploy": "gh-pages -d build"
      }
    • 运行 npm run deploy

React 生态系统丰富而充满活力,持续学习和实践是掌握它的关键。记住,最好的学习方式是构建真实项目——尝试扩展这个计数器应用,或者开始一个全新的项目! 

相关文章:

  • 嵌入式C语言进阶(二+)内存管理补充版
  • nvm切换node版本后,解决npm找不到的问题
  • Web前端 (CSS篇)
  • MyBatis:SpringBoot结合MyBatis、MyBatis插件机制的原理分析与实战
  • Shell编程之正则表达式与文本
  • Tomcat大版本升级教程
  • B端可视化方案,如何助力企业精准决策,抢占市场先机
  • MyBatis与MyBatis-Plus:字段自动填充的两种实现方式
  • 【Netty篇】Future Promise 详解
  • 【物联网】基于LORA组网的远程环境监测系统设计
  • 医疗大模型落地方案:技术选型、部署策略与调优
  • 与/或形演绎推理——基于王永庆著《人工智能原理与方法》的深度解析
  • GitHub 趋势日报 (2025年04月15日)
  • OpenCV操作函数
  • kafka服务端和springboot中使用
  • Excel数据自动填充到Word自定义表格
  • OpenCV day4
  • ESP-ADF外设子系统深度解析:esp_peripherals组件架构与核心设计(输入类外设之按键Button)
  • Spark-SQL核心编程3
  • Python爬虫第15节-2025今日头条街拍美图抓取实战
  • 苹果网站导航条/电话营销技巧和营销方法
  • 有什么做外贸的好网站/重庆seo网络推广关键词
  • 电影网站页面seo/竞价推广账户竞价托管费用
  • 邯郸信息港交友/真实有效的优化排名
  • 广东网站建设公司哪家便宜/网上推广app怎么做
  • 什么网站做优化最好?/seo网站搜索优化