React State 与事件
目标:用
useState做交互;理解「事件 → 更新 state → 重渲染」。
动手
完整代码:react2/03-state-events/demo
bash
cd react2/03-state-events/demo
npm install
npm run dev
流程
- 用户点击 / 输入
- 事件处理函数调用
setXxx - React 用新 state 重新执行组件函数
- 屏幕更新
tsx
const [count, setCount] = useState(0)
<button onClick={() => setCount((c) => c + 1)}>+1</button>
输入框用受控组件 :value 绑 state,onChange 写回 state。
运行截图

坑
| 做法 | 为什么不好 |
|---|---|
count++ 直接改 |
state 必须不可变更新,用 setCount |
setCount(count + 1) 连点多次 |
可能读到旧值;优先 setCount(c => c + 1) |