Files
DailyChallenge_APPDepartment/Day_5/README.md
T
arthur 3284e63e89 init
2026-09-17 11:13:35 +08:00

68 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Day_5:让页面动起来——事件、state 与 useState
预计用时:40~60 分钟。
## 今日目标
- 理解“事件 → 函数 → state 更新 → 界面更新”
- 使用 `Pressable`
- 使用 `useState`
- 完成学习打卡计数器
## 1. state 是什么
页面中会变化的数据叫状态(state)。在函数组件中,用 `useState` 保存它:
```tsx
import { useState } from 'react';
const [count, setCount] = useState(0);
```
`count` 是当前数值;`setCount` 是更新它的方式。调用后,React 会重新渲染受影响的界面。
## 2. 加一个按钮
```tsx
import { Pressable, Text, View } from 'react-native';
<View>
<Text>今日学习次数:{count}</Text>
<Pressable onPress={() => setCount(count + 1)}>
<Text>+1</Text>
</Pressable>
</View>
```
用户点击 `Pressable`,触发 `onPress`,再通过 `setCount` 更新数值;`Text` 中的 `{count}` 会显示新值。
## 今日任务:学习打卡计数器
在昨天的个人信息卡片下方加入计数器:
```text
今日学习打卡
当前完成:0 次
[ +1 ] [ -1 ] [ 重置 ]
```
要求:`+1` 增加一次;`-1` 减少一次但不能小于 0;重置按钮使次数回到 0;为按钮添加明显的背景色、内边距和圆角。
`-1` 的逻辑可以写成:
```tsx
setCount((current) => Math.max(0, current - 1));
```
## 验收标准
- [ ] 使用 `useState`
- [ ] 使用至少一个 `Pressable`
- [ ] `+1`、`-1`、重置均可用
- [ ] 数值不会小于 0
- [ ] 点击后界面会立即更新
## 思考题
为什么不要写 `count++`,而要调用 `setCount`?提示:React 需要知道状态发生了变化,才能安排重新渲染。