React 快速上手教程
React 快速上手建议直接用 React 19 + Vite + TypeScript,按"环境 → 建项目 → 写组件 → 状态管理 → 跑起来"这条主线,10 分钟就能写出第一个交互式页面。
1. 准备环境
需要:
- Node.js 20.x LTS 或以上
- VS Code 或你习惯的编辑器
- 浏览器装一个 React DevTools 扩展(调试用)
验证环境:
node -v
npm -v2. 用 Vite 创建项目
Vite 是 2026 年 React 官方推荐的构建工具,冷启动秒开,热更新毫秒级。
npm create vite@latest my-react-app -- --template react-ts
cd my-react-app
npm install
npm run dev启动成功后浏览器打开 http://localhost:5173,看到 React 欢迎页即成功。
注意:Vite 的 React 模板默认可能装的是 React 18,创建后检查 package.json,确保 react 和 react-dom 是 ^19.x。
3. 写第一个组件
打开 src/App.tsx,替换为:
import { useState } from 'react'
function App() {
const [count, setCount] = useState(0)
return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h1>React 19 快速上手</h1>
<p>你点了 {count} 次</p>
<button onClick={() => setCount(count + 1)}>
点我
</button>
</div>
)
}
export default App保存后浏览器自动刷新,点击按钮数字递增。这就是 React 的核心心智模型:UI = f(state)——状态变了,界面自动更新。
4. 理解几个核心概念
JSX:在 JavaScript 里写 HTML 标签的语法糖,最终编译成 React.createElement() 调用。
Props:父组件传给子组件的数据,类似函数参数:
function Greeting({ name }: { name: string }) {
return <h2>你好,{name}!</h2>
}
// 使用:<Greeting name="React" />useState:最基础的状态 Hook,返回 [当前值, 更新函数]。
useEffect:处理副作用(数据请求、订阅等),等价于生命周期中的"挂载后/更新后":
import { useEffect, useState } from 'react'
function UserList() {
const [users, setUsers] = useState([])
useEffect(() => {
fetch('/api/users')
.then(res => res.json())
.then(data => setUsers(data))
}, []) // 空数组 = 只在挂载时执行一次
return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>
}5. React 19 新写法速览
use() Hook:直接在组件里读取 Promise,配合 Suspense 使用,替代 useEffect + useState 的异步模式:
import { use, Suspense } from 'react'
function UserProfile({ userPromise }: { userPromise: Promise<any> }) {
const user = use(userPromise)
return <div>{user.name}</div>
}
// 使用
<Suspense fallback={<p>加载中...</p>}>
<UserProfile userPromise={fetch('/api/user').then(r => r.json())} />
</Suspense>Form Actions:表单提交不再需要手动管理 loading 状态:
import { useActionState } from 'react'
async function submitForm(prev: any, formData: FormData) {
const name = formData.get('name')
await fetch('/api/submit', { method: 'POST', body: JSON.stringify({ name }) })
return { ok: true }
}
function MyForm() {
const [state, action, isPending] = useActionState(submitForm, null)
return (
<form action={action}>
<input name="name" placeholder="姓名" />
<button disabled={isPending}>{isPending ? '提交中...' : '提交'}</button>
</form>
)
}6. 项目目录建议
src/
├── components/ # 可复用组件
├── pages/ # 页面组件
├── hooks/ # 自定义 Hooks
├── services/ # API 请求
├── App.tsx # 根组件
└── main.tsx # 入口文件7. 下一步
- 加路由:
npm install react-router-dom,用 React Router 做多页面跳转 - 接后端:用
fetch或axios调你之前写的 Spring Boot / Django API - 加样式:Tailwind CSS 或 Ant Design 任选
- 上生产:
npm run build打包,部署到 Vercel / Netlify / Nginx