如何在React中实现待办事项(Todo)列表的删除功能
给React待办事项列表添加删除功能的实现方法
要给这个待办列表加上删除功能,分两步就能搞定:
1. 编写删除任务的函数
在组件里新增一个deleteTask函数,它接收要删除项的索引,通过过滤数组生成新列表(React中不能直接修改原状态数组,必须生成新数组更新状态):
const deleteTask = (index) => { // 过滤掉当前索引对应的项,生成新数组 const updatedList = list.filter((_, i) => i !== index); setList(updatedList); };
2. 给每个待办项添加删除按钮
在渲染待办项的map方法里,给每个待办内容旁加上删除按钮,点击时调用deleteTask并传入当前项的索引:
{list.map((el, index) => { return ( <div key={index} style={{ display: "flex", gap: "10px", alignItems: "center" }}> <p>{el}</p> <button style={{ height: "25px", borderRadius: "10px", backgroundColor: "#ff4444", color: "white", border: "none", cursor: "pointer" }} onClick={() => deleteTask(index)} > 删除 </button> </div> ); })}
完整修改后的代码
整合所有改动后的完整组件代码如下,还顺手优化了一些体验细节:
"use client"; import { useState } from "react"; export default function Home() { const [value, setValue] = useState(""); const [list, setList] = useState([]); const handleChange = (e) => { setValue(e.target.value); }; const addTask = () => { // 避免添加空任务 if (!value.trim()) return; const arraycopy = [...list, value]; setList(arraycopy); // 添加后清空输入框 setValue(""); }; const deleteTask = (index) => { const updatedList = list.filter((_, i) => i !== index); setList(updatedList); }; return ( <div style={{ padding: "20px" }}> <div> <h4 style={{ width: "250px", height: "50px", backgroundColor: "#1C89B6", color: "white", margin: "0 0 20px 0", display: "flex", alignItems: "center", justifyContent: "center" }} > 我的待办清单 </h4> </div> {list.map((el, index) => { return ( <div key={index} style={{ display: "flex", gap: "10px", marginBottom: "10px", alignItems: "center" }}> <p style={{ margin: 0 }}>{el}</p> <button style={{ height: "25px", borderRadius: "10px", backgroundColor: "#ff4444", color: "white", border: "none", cursor: "pointer", padding: "0 10px" }} onClick={() => deleteTask(index)} > 删除 </button> </div> ); })} <div style={{ marginTop: "20px", display: "flex", gap: "10px", alignItems: "center" }}> <input style={{ width: "200px", height: "30px", borderRadius: "20px", padding: "0 10px" }} value={value} onChange={handleChange} placeholder="接下来要做什么?" /> <button style={{ width: "100px", height: "30px", borderRadius: "20px", display: "flex", alignItems: "center", justifyContent: "center", backgroundColor: "#1C89B6", color: "white", border: "none", cursor: "pointer" }} onClick={addTask} > 添加 </button> </div> </div> ); }
优化细节说明:
- 添加任务时判断输入是否为空,避免无效的空项
- 任务添加完成后自动清空输入框
- 调整了布局样式,让界面排版更整齐
内容的提问来源于stack exchange,提问作者Hangai
相关产品推荐
相关产品推荐

