文章目录
- [一、认识 React](#一、认识 React)
-
- [1.1 核心特点](#1.1 核心特点)
- [二、快速搭建 React 项目](#二、快速搭建 React 项目)
-
- [2.1 使用 Create React App](#2.1 使用 Create React App)
- [2.2 使用 Vite 创建更轻量的 React 项目](#2.2 使用 Vite 创建更轻量的 React 项目)
- [2.3 项目结构概览](#2.3 项目结构概览)
- [三、React 核心语法基础](#三、React 核心语法基础)
-
- [3.1 JSX:React 的模板语法](#3.1 JSX:React 的模板语法)
- [3.2 函数组件与 Props](#3.2 函数组件与 Props)
- [3.3 useState:定义响应式状态](#3.3 useState:定义响应式状态)
- [3.4 条件渲染](#3.4 条件渲染)
- [3.5 列表渲染](#3.5 列表渲染)
- [3.6 useEffect:副作用管理](#3.6 useEffect:副作用管理)
- 四、组件通信方式详解
-
- [4.1 父 → 子(props)](#4.1 父 → 子(props))
- [4.2 子 → 父(回调函数)](#4.2 子 → 父(回调函数))
- [4.3 跨层通信:Context](#4.3 跨层通信:Context)
- [五、React Router 路由配置](#五、React Router 路由配置)
-
- [5.1 安装](#5.1 安装)
- [5.2 使用 BrowserRouter 和 Routes](#5.2 使用 BrowserRouter 和 Routes)
- [5.3 路由跳转和传参](#5.3 路由跳转和传参)
- [六、状态管理(Redux Toolkit)](#六、状态管理(Redux Toolkit))
-
- [6.1 安装依赖](#6.1 安装依赖)
- [6.2 创建切片和 Store](#6.2 创建切片和 Store)
- [6.3 在组件中使用](#6.3 在组件中使用)
- 七、进阶技巧与性能优化
-
- [7.1 React.memo](#7.1 React.memo)
- [7.2 useCallback / useMemo](#7.2 useCallback / useMemo)
- [7.3 异步数据处理:React Query 示例](#7.3 异步数据处理:React Query 示例)
- [八、推荐的 React 技术栈生态](#八、推荐的 React 技术栈生态)
-
- [8.1 网络请求:axios + swr](#8.1 网络请求:axios + swr)
-
- [axios 简用法:](#axios 简用法:)
- [swr 使用(自动缓存 + 重试):](#swr 使用(自动缓存 + 重试):)
- [8.2 表单处理:react-hook-form](#8.2 表单处理:react-hook-form)
- [8.3 状态管理:Redux Toolkit + Zustand(更轻)](#8.3 状态管理:Redux Toolkit + Zustand(更轻))
- [8.4 动画库:Framer Motion](#8.4 动画库:Framer Motion)
- [8.5 UI 框架推荐](#8.5 UI 框架推荐)
- [8.6 构建工具推荐](#8.6 构建工具推荐)
- 九、部署与上线
-
- [9.1 构建项目](#9.1 构建项目)
- [9.2 免费部署平台](#9.2 免费部署平台)
- 十、总结与学习路径建议
一、认识 React
React 是由 Facebook 开发的构建用户界面的 JavaScript 库。它通过组件化的开发方式提高了 UI 复用能力,是现代前端开发的核心技术之一。
1.1 核心特点
- 基于组件:构建复杂 UI 就像搭积木。
- 虚拟 DOM:高效的 UI 更新策略。
- 单向数据流:更易于维护和调试。
- 声明式编程:代码更简洁、更可预测。
二、快速搭建 React 项目
2.1 使用 Create React App
bash
npx create-react-app my-app
cd my-app
npm start
2.2 使用 Vite 创建更轻量的 React 项目
bash
npm create vite@latest my-app --template react
cd my-app
npm install
npm run dev
2.3 项目结构概览
txt
my-app/
├── src/
│ ├── App.jsx
│ ├── main.jsx
│ ├── components/
├── public/
├── index.html
└── package.json
三、React 核心语法基础
3.1 JSX:React 的模板语法
jsx
const element = <h1>Hello, React!</h1>;
注意事项:
- 使用
className替代class; - 表达式用
{}包裹; - 标签必须闭合。
3.2 函数组件与 Props
jsx
function Welcome(props) {
return <h1>欢迎, {props.name}</h1>;
}
<Welcome name="张三" />
3.3 useState:定义响应式状态
jsx
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<>
<p>当前数量:{count}</p>
<button onClick={() => setCount(count + 1)}>+1</button>
</>
);
}
3.4 条件渲染
jsx
{isLogin ? <p>欢迎回来</p> : <p>请登录</p>}
3.5 列表渲染
jsx
const users = ['Tom', 'Jerry', 'Lucy'];
<ul>
{users.map((name, i) => <li key={i}>{name}</li>)}
</ul>
3.6 useEffect:副作用管理
jsx
useEffect(() => {
console.log('组件已挂载');
return () => {
console.log('组件已卸载');
};
}, []);
四、组件通信方式详解
4.1 父 → 子(props)
jsx
function Child({ msg }) {
return <p>{msg}</p>;
}
function Parent() {
return <Child msg="来自父组件" />;
}
4.2 子 → 父(回调函数)
jsx
function Child({ onSend }) {
return <button onClick={() => onSend('hello')}>点击传值</button>;
}
function Parent() {
const handleMsg = (msg) => console.log(msg);
return <Child onSend={handleMsg} />;
}
4.3 跨层通信:Context
jsx
const ThemeContext = createContext();
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
return <ThemedButton />;
}
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={theme}>按钮</button>;
}
五、React Router 路由配置
5.1 安装
bash
npm install react-router-dom
5.2 使用 BrowserRouter 和 Routes
jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
5.3 路由跳转和传参
jsx
<Link to="/about">跳转到 About</Link>
const navigate = useNavigate();
navigate('/about');
六、状态管理(Redux Toolkit)
6.1 安装依赖
bash
npm install @reduxjs/toolkit react-redux
6.2 创建切片和 Store
js
// counterSlice.js
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: 0,
reducers: {
increment: (state) => state + 1
}
});
export const { increment } = counterSlice.actions;
export default counterSlice.reducer;
js
// store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';
export const store = configureStore({
reducer: {
counter: counterReducer
}
});
6.3 在组件中使用
jsx
import { useSelector, useDispatch } from 'react-redux';
import { increment } from './counterSlice';
function Counter() {
const count = useSelector(state => state.counter);
const dispatch = useDispatch();
return (
<div>
<p>当前:{count}</p>
<button onClick={() => dispatch(increment())}>+1</button>
</div>
);
}
七、进阶技巧与性能优化
7.1 React.memo
jsx
const MyComponent = React.memo(({ value }) => {
return <div>{value}</div>;
});
7.2 useCallback / useMemo
jsx
const handleClick = useCallback(() => {
console.log('click');
}, []);
const expensiveValue = useMemo(() => {
return computeSomething();
}, [input]);
7.3 异步数据处理:React Query 示例
bash
npm install @tanstack/react-query
jsx
import { useQuery } from '@tanstack/react-query';
const { data, isLoading } = useQuery(['todos'], fetchTodos);
八、推荐的 React 技术栈生态
React 周边生态繁荣,推荐以下实用库,并结合使用场景:
8.1 网络请求:axios + swr
axios 简用法:
js
import axios from 'axios';
axios.get('/api/user').then(res => {
console.log(res.data);
});
swr 使用(自动缓存 + 重试):
jsx
import useSWR from 'swr';
const fetcher = url => fetch(url).then(res => res.json());
function User() {
const { data, error } = useSWR('/api/user', fetcher);
if (error) return <div>加载失败</div>;
if (!data) return <div>加载中...</div>;
return <div>用户名: {data.name}</div>;
}
8.2 表单处理:react-hook-form
bash
npm install react-hook-form
jsx
import { useForm } from 'react-hook-form';
function Form() {
const { register, handleSubmit } = useForm();
const onSubmit = data => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
<input type="submit" />
</form>
);
}
8.3 状态管理:Redux Toolkit + Zustand(更轻)
Zustand 示例:
bash
npm install zustand
js
import create from 'zustand';
const useStore = create(set => ({
count: 0,
inc: () => set(state => ({ count: state.count + 1 }))
}));
function Counter() {
const { count, inc } = useStore();
return <button onClick={inc}>Count: {count}</button>;
}
8.4 动画库:Framer Motion
bash
npm install framer-motion
jsx
import { motion } from 'framer-motion';
<motion.div animate={{ x: 100 }} transition={{ duration: 1 }} />
8.5 UI 框架推荐
| 框架 | 特点 |
|---|---|
| Ant Design | 企业级组件,规范统一 |
| MUI | Google Material 风格 |
| Chakra UI | 原子化、可组合性强的设计 |
使用 MUI 示例:
bash
npm install @mui/material @emotion/react @emotion/styled
jsx
import Button from '@mui/material/Button';
<Button variant="contained">按钮</Button>
8.6 构建工具推荐
| 工具 | 特点 |
|---|---|
| Vite | 快速启动,ESM 原生支持 |
| Webpack | 插件/配置丰富,老牌稳定 |
| Parcel | 零配置、快速构建 |
Vite 优势:默认支持 JSX、HMR 热更新,推荐作为主流 React 项目的构建工具。
九、部署与上线
9.1 构建项目
bash
npm run build
9.2 免费部署平台
- Vercel:https://vercel.com
- Netlify:https://netlify.com
- Github Pages:通过 gh-pages 插件
十、总结与学习路径建议
React 是现代前端开发者必备技能。学习路线推荐:
- 掌握 JSX、Hooks、组件设计;
- 深入状态管理与路由;
- 理解性能优化与大型项目结构;
- 延伸学习 Next.js、React Native、TS+React 项目实战等。
到这里,这篇文章就和大家说再见啦!我的主页里还藏着很多 篇 前端 实战干货,感兴趣的话可以点击头像看看,说不定能找到你需要的解决方案~
创作这篇内容花了很多的功夫。如果它帮你解决了问题,或者带来了启发,欢迎:
点个赞❤️ 让更多人看到优质内容
关注「前端极客探险家」🚀 每周解锁新技巧
收藏文章⭐️ 方便随时查阅
📢 特别提醒:
转载请注明原文链接,商业合作请私信联系
感谢你的阅读!我们下篇文章再见~ 💕
