Skip to content

Todo 列表 App

简单 约 25 分钟

你将构建什么

todo 列表 app 哪里你 能添加新 项, mark 项 as 完整 (使用 strikethrough), and 删除项. 每个项 有唯一 ID generated 使用 Date.现在().

学习目标

  • Manage 数组状态使用 useState
  • 渲染列表使用 .映射() and 唯一键
  • 构建 controlled 输入 for 添加 todos
  • 更新数组 immutably (spread 运算符)

前置要求

  • useState 基础
  • 数组方法 (映射, 筛选)
  • JSX 语法

步骤

  1. 1

    设置状态 and 输入表单

    创建 TodoList 组件使用 todos 数组状态 and 文本输入状态 for 新 todo.

    代码
    const [todos, setTodos] = useState([]);
    const [text, setText] = useState("");

    预期结果

    空状态是 ready for 添加 todos.

  2. 2

    添加 addTodo 函数

    创建函数那个添加新 todo 对象使用唯一 id, current 文本, and 已完成: 假. 清晰输入之后添加.

    代码
    const addTodo = () => {
      if (!text.trim()) return;
      setTodos([...todos, { id: Date.now(), text, completed: false }]);
      setText("");
    };

    预期结果

    输入 and 点击添加创建新 todo 项.

  3. 3

    渲染 todo 列表

    映射 over todos and 渲染每个使用 checkbox, 文本, and 删除 button. Use todo id as 键.

    代码
    {todos.map(todo => (
      <li key={todo.id}>
        <input type="checkbox" checked={todo.completed}
          onChange={() => toggleTodo(todo.id)} />
        <span style={{ textDecoration: todo.completed ? "line-through" : "none" }}>
          {todo.text}
        </span>
        <button onClick={() => deleteTodo(todo.id)}>Delete</button>
      </li>
    ))}

    预期结果

    所有 todos 是 displayed 使用 checkboxes and 删除 buttons.

  4. 4

    Implement 切换 and 删除函数

    toggleTodo 映射 over todos and flips 已完成 flag for matching id. deleteTodo 筛选 out matching id.

    代码
    const toggleTodo = (id) => {
      setTodos(todos.map(t => t.id === id ? { ...t, completed: !t.completed } : t));
    };
    
    const deleteTodo = (id) => {
      setTodos(todos.filter(t => t.id !== id));
    };

    预期结果

    检查 checkbox strikes 通过文本. 删除移除项.

  5. 5

    添加状态管理与事件处理

    使用 useState 管理组件状态,为交互元素添加 onClick/onChange 事件处理。状态是 React 组件的核心,事件处理让组件响应用户操作。

    代码
    import { useState } from "react";
    
    export function MyComponent() {
      const [count, setCount] = useState(0);
      const [text, setText] = useState("");
    
      return (
        <div>
          <button onClick={() => setCount(c => c + 1)}>
            Count: {count}
          </button>
          <input
            value={text}
            onChange={(e) => setText(e.target.value)}
          />
        </div>
      );
    }

    预期结果

    点击按钮计数递增;输入框内容随键入实时更新。

自己动手试试

你学到了什么

你练习不可变数组状态更新 (spread for 添加, 映射 for 切换, 筛选 for 删除), 列表渲染使用键, and controlled 输入 — 核心模式 for managing 集合 in React.

相关资源

相关课程

相关练习

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题