01-React基础入门——01-React概述与环境搭建
·

React概述与环境搭建
一、React是什么?
1.1 5W1H分析
/**
* 5W1H 分析:React
*
* What: React 是一个用于构建用户界面的 JavaScript 库
* Why: 解决 DOM 操作复杂、状态管理困难、性能优化难的问题
* Who: 前端开发者、全栈开发者、UI工程师
* When: 构建单页应用(SPA)、复杂交互界面、组件化开发
* Where: Web应用、移动端(React Native)、桌面应用(Electron + React)
* How: 组件化开发、声明式UI、虚拟DOM、单向数据流
*/
console.log("=" .repeat(60));
console.log("React 19 学习路线 - 第1篇:React概述与环境搭建");
console.log("=" .repeat(60));
// React 核心特点演示
const reactFeatures = {
声明式UI: "描述UI应该呈现的状态,React负责更新DOM",
组件化: "将UI拆分为独立、可复用的组件",
虚拟DOM: "高效的DOM更新策略",
单向数据流: "数据从父组件流向子组件",
JSX: "JavaScript XML语法扩展"
};
console.log("\n📌 React核心特点:");
Object.entries(reactFeatures).forEach(([key, value]) => {
console.log(` ${key}: ${value}`);
});
1.2 传统方式 vs React方式
// 传统方式(命令式)- 手动操作DOM
function traditionalCounter() {
let count = 0;
const element = document.getElementById('app');
function updateUI() {
element.innerHTML = `
<div class="counter">
<h1>计数器: ${count}</h1>
<button onclick="window.increment()">增加</button>
</div>
`;
}
window.increment = () => {
count++;
updateUI();
};
updateUI();
}
// React方式(声明式)- 描述UI,自动更新
import { useState } from 'react';
function ReactCounter() {
const [count, setCount] = useState(0);
return (
<div className="counter">
<h1>计数器: {count}</h1>
<button onClick={() => setCount(count + 1)}>增加</button>
</div>
);
}
1.3 React 19 新特性
/**
* React 19 主要新特性
*/
// 1. React Compiler - 自动记忆化
// 无需手动使用 useMemo、useCallback、React.memo
// 2. Actions - 简化表单处理
function FormWithActions() {
const [error, submitAction, isPending] = useActionState(
async (previousState, formData) => {
const name = formData.get('name');
const email = formData.get('email');
try {
await saveToDatabase({ name, email });
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
},
{ success: false, error: null }
);
return (
<form action={submitAction}>
<input name="name" type="text" />
<input name="email" type="email" />
<button type="submit" disabled={isPending}>
{isPending ? '提交中...' : '提交'}
</button>
{error && <p className="error">{error}</p>}
</form>
);
}
// 3. use hook - 读取Promise和Context
import { use } from 'react';
function Comments({ commentsPromise }) {
// use hook 可以直接消费 Promise
const comments = use(commentsPromise);
return (
<ul>
{comments.map(comment => (
<li key={comment.id}>{comment.text}</li>
))}
</ul>
);
}
// 4. useOptimistic - 乐观更新
function LikeButton() {
const [likes, setLikes] = useState(0);
const [optimisticLikes, setOptimisticLikes] = useOptimistic(
likes,
(currentState, optimisticValue) => currentState + optimisticValue
);
const handleLike = async () => {
setOptimisticLikes(1);
await api.likePost();
setLikes(l => l + 1);
};
return (
<button onClick={handleLike}>
点赞数: {optimisticLikes}
</button>
);
}
二、开发环境搭建
2.1 前置要求
# 检查Node.js版本(需要18.0或更高)
node --version
# 检查npm版本
npm --version
# 如果没有安装Node.js,请前往 https://nodejs.org 下载安装
2.2 方式一:Vite(推荐)
# 创建项目
npm create vite@latest my-react-app -- --template react
# 进入项目目录
cd my-react-app
# 安装依赖
npm install
# 启动开发服务器
npm run dev
# 构建生产版本
npm run build
# 预览生产版本
npm run preview
2.3 方式二:Create React App(传统)
# 创建项目
npx create-react-app my-app
# 进入项目目录
cd my-app
# 启动开发服务器
npm start
# 构建生产版本
npm run build
# 运行测试
npm test
# eject(不可逆,暴露配置)
npm run eject
2.4 方式三:Next.js(生产级)
# 创建项目
npx create-next-app@latest my-next-app
# 进入项目目录
cd my-next-app
# 启动开发服务器
npm run dev
# 构建生产版本
npm run build
# 启动生产服务器
npm start
2.5 方式对比
| 特性 | Vite | CRA | Next.js |
|---|---|---|---|
| 启动速度 | 极快 | 慢 | 快 |
| 构建速度 | 快 | 慢 | 快 |
| 配置灵活性 | 高 | 低 | 中 |
| 服务端渲染 | 需要配置 | 不支持 | 原生支持 |
| 路由 | 自行配置 | 自行配置 | 文件路由 |
| 适用场景 | 通用 | 学习/小型项目 | 生产级应用 |
三、项目结构解析
3.1 Vite项目结构
my-react-app/
├── index.html # 入口HTML文件
├── package.json # 项目依赖配置
├── vite.config.js # Vite配置文件
├── public/ # 静态资源目录
│ └── vite.svg
├── src/ # 源代码目录
│ ├── main.jsx # 应用入口
│ ├── App.jsx # 根组件
│ ├── App.css # 根组件样式
│ ├── index.css # 全局样式
│ └── assets/ # 资源文件
└── node_modules/ # 依赖包
3.2 入口文件解析
// src/main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
// React 18+ 使用 createRoot
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
3.3 根组件解析
// src/App.jsx
import { useState } from 'react';
import './App.css';
function App() {
const [count, setCount] = useState(0);
return (
<div className="app">
<header className="app-header">
<h1>React 19 学习之旅</h1>
<p>欢迎来到React世界!</p>
<button onClick={() => setCount(count + 1)}>
点击次数: {count}
</button>
</header>
</div>
);
}
export default App;
四、第一个React组件
4.1 创建简单组件
// src/components/Greeting.jsx
function Greeting({ name }) {
return (
<div className="greeting">
<h2>你好,{name}!</h2>
<p>欢迎学习React 19</p>
</div>
);
}
export default Greeting;
4.2 使用组件
// src/App.jsx
import Greeting from './components/Greeting';
function App() {
return (
<div className="app">
<Greeting name="React学习者" />
<Greeting name="前端开发者" />
</div>
);
}
export default App;
4.3 带状态的组件
// src/components/Counter.jsx
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => setCount(c => c + 1);
const decrement = () => setCount(c => c - 1);
const reset = () => setCount(0);
return (
<div className="counter">
<h2>计数器: {count}</h2>
<div className="counter-buttons">
<button onClick={decrement}>-1</button>
<button onClick={reset}>重置</button>
<button onClick={increment}>+1</button>
</div>
</div>
);
}
export default Counter;
五、配置文件详解
5.1 Vite配置
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
server: {
port: 3000,
open: true,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
},
build: {
outDir: 'dist',
sourcemap: true,
minify: 'terser',
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom']
}
}
}
},
resolve: {
alias: {
'@': '/src',
'@components': '/src/components'
}
}
});
5.2 package.json详解
{
"name": "my-react-app",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"lint": "eslint src --ext js,jsx",
"format": "prettier --write src"
},
"dependencies": {
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.0.0",
"vite": "^5.0.0"
}
}
六、开发者工具
6.1 React DevTools安装
# Chrome/Edge浏览器
# 访问 Chrome Web Store 搜索 "React Developer Tools" 安装
# Firefox浏览器
# 访问 Firefox Add-ons 搜索 "React Developer Tools" 安装
6.2 使用React DevTools
// React DevTools 可以帮助你:
// 1. 查看组件树结构
// 2. 检查组件的props和state
// 3. 性能分析(Profiler)
// 4. 高亮渲染更新
// 在组件中添加displayName便于调试
function MyComponent() {
return <div>My Component</div>;
}
MyComponent.displayName = 'CustomMyComponent';
6.3 VSCode推荐插件
// .vscode/extensions.json
{
"recommendations": [
"dsznajder.es7-react-js-snippets",
"esbenp.prettier-vscode",
"dbaeumer.vscode-eslint",
"bradlc.vscode-tailwindcss",
"formulahendry.auto-rename-tag",
"aaron-bond.better-comments"
]
}
七、常见问题与解决
7.1 端口占用
# 查看端口占用(Mac/Linux)
lsof -i :3000
# 杀死进程
kill -9 <PID>
# 或使用不同端口
npm run dev -- --port 3001
7.2 依赖安装失败
# 清除缓存重试
npm cache clean --force
rm -rf node_modules package-lock.json
npm install
# 使用国内镜像
npm config set registry https://registry.npmmirror.com
7.3 版本兼容问题
# 查看当前版本
npm list react react-dom
# 升级到最新版本
npm install react@latest react-dom@latest
八、总结
8.1 本节知识点回顾
| 知识点 | 说明 | 掌握程度 |
|---|---|---|
| React概念 | 声明式UI、组件化、虚拟DOM | ⭐⭐⭐⭐⭐ |
| 环境搭建 | Vite、CRA、Next.js | ⭐⭐⭐⭐ |
| 项目结构 | 目录结构、入口文件 | ⭐⭐⭐⭐ |
| 第一个组件 | 函数组件、JSX | ⭐⭐⭐⭐⭐ |
| 配置文件 | vite.config.js | ⭐⭐⭐ |
| 开发者工具 | React DevTools | ⭐⭐⭐⭐ |
8.2 练习任务
// 练习1:创建一个个人信息卡片组件
// 要求:包含姓名、年龄、职业、头像
function ProfileCard() {
// 实现代码
return <div>...</div>;
}
// 练习2:创建一个待办事项列表组件
// 要求:能够添加、删除、标记完成
function TodoList() {
// 实现代码
return <div>...</div>;
}
// 练习3:创建一个计数器组件
// 要求:支持增加、减少、重置、设置步长
function AdvancedCounter() {
// 实现代码
return <div>...</div>;
}
8.3 下一步预告
下一篇将学习 JSX语法详解,内容包括:
- JSX基础语法
- 表达式嵌入
- 条件渲染
- 列表渲染
- 样式处理
更多推荐


所有评论(0)