我的 React 之旅:第 28 天
在 React 中创建待办事项列表
今天,我参与了一个 React 项目,创建了一个简单但功能强大的“待办事项列表应用”。这个项目加深了我对“React 钩子”、“状态管理”和“事件处理”的理解,同时允许我使用其他功能(如上移或下移任务)来增强功能。
以下是我所学和所实施内容的细目。
**1. 设置组件**
我构建了 `ToDoList.jsx` 以使用 `useState hook` 来管理任务。这允许我动态更新和呈现任务列表。以下是管理任务的基本设置:
import React, { useState } from 'react'; export default function ToDoList() { const [tasks, setTasks] = useState([]); const [newTask, setNewTask] = useState(""); function handleInputChange(event) { setNewTask(event.target.value); // Enables us to see what we type } function addTask() { if (newTask.trim() !== "") { setTasks(t => [...t, newTask]); // Adds the new task to the task list setNewTask(""); // Resets the input field } } }
**2. 添加和删除任务**
我学习了如何操纵状态来添加和删除任务。`addTask` 函数在添加之前检查输入是否有效,而 `deleteTask` 则根据索引删除特定任务:
function deleteTask(index) { const updatedTasks = tasks.filter((_, i) => i !== index); // Removes the task at the given index setTasks(updatedTasks); }
**3. 上下移动任务**
该项目的一项重要改进是实现任务重新排序。`moveTaskUp` 和 `moveTaskDown` 函数根据索引重新排列任务:
function moveTaskUp(index) { if (index > 0) { const updatedTasks = [...tasks]; [updatedTasks[index], updatedTasks[index - 1]] = [updatedTasks[index - 1], updatedTasks[index]]; setTasks(updatedTasks); } } function moveTaskDown(index) { if (index < tasks.length - 1) { const updatedTasks = [...tasks]; [updatedTasks[index], updatedTasks[index + 1]] = [updatedTasks[index + 1], updatedTasks[index]]; setTasks(updatedTasks); } }
**4. 使用 CSS 添加样式**
为了让应用程序看起来更具吸引力,我在“index.css”中应用了自定义样式。以下是一些亮点:
**按钮样式:**
button { font-size: 1.7rem; font-weight: bold; padding: 10px 20px; color: white; border: none; border-radius: 5px; cursor: pointer; transition: background-color 0.5s ease; } .add-button { background-color: hsl(125, 47%, 54%); } .add-button:hover { background-color: hsl(125, 47%, 44%); }
**任务项样式:**
li { font-size: 2rem; font-weight: bold; padding: 15px; background-color: hsl(0, 0%, 97%); margin-bottom: 10px; border: 3px solid hsla(0, 0%, 85%, 0.75); border-radius: 5px; display: flex; align-items: center; }
**5. 完整待办事项列表**
以下是 `ToDoList.jsx` 组件中所有内容的组合方式:
return ();To-Do List
{tasks.map((task, index) => (
- {task}
))}
关键要点
**一步一个脚印**
**源代码**
您可以在 GitHub 上访问该项目的完整源代码:
👉 待办事项列表 React App 存储库
欢迎随意探索、分叉并为该项目做出贡献!