一个使用React实现简单待办事项列表,一个基本的组件结构和必要的功能,
jsxCopy code
import React, { useState } from 'react';
const TodoList = () => {
const [todos, setTodos] = useState([]);
const [currentTodo, setCurrentTodo] = useState('');
const [editingIndex, setEditingIndex] = useState(-1);
const handleAddTodo = () => {
if (currentTodo.trim() === '') return;
if (editingIndex === -1) {
setTodos([...todos, currentTodo]);
} else {
const updatedTodos = [...todos];
updatedTodos[editingIndex] = currentTodo;
setTodos(updatedTodos);
setEditingIndex(-1);
}
setCurrentTodo('');
};
const handleEditTodo = (index) => {
setCurrentTodo(todos[index]);
setEditingIndex(index);
};
const handleDeleteTodo = (index) => {
const updatedTodos = todos.filter((_, i) => i !== index);
setTodos(updatedTodos);
};
return (
<div>
<h1>Todo List</h1>
<input
type="text"
value={currentTodo}
onChange={(e) => setCurrentTodo(e.target.value)}
placeholder="Enter a todo"
/>
<button onClick={handleAddTodo}>{editingIndex === -1 ? 'Add' : 'Update'}</button>
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo}
<button onClick={() => handleEditTodo(index)}>Edit</button>
<button onClick={() => handleDeleteTodo(index)}>Delete</button>
</li>
))}
</ul>
</div>
);
};
export default TodoList;
-
首先,我们导入了React和
useState钩子,用于在函数组件中管理状态。 -
创建一个名为
TodoList的函数组件。这个组件将包含整个待办事项列表的逻辑和UI。 -
在组件内部,我们使用了三个状态变量:
todos:一个数组,用于存储所有待办事项的文本。currentTodo:一个字符串,用于存储当前正在输入的待办事项文本。editingIndex:一个数字,用于跟踪当前正在编辑的待办事项在todos数组中的索引。如果没有任何事项处于编辑状态,它的值为-1。
-
在UI部分,我们渲染了以下元素:
-
一个标题,显示 "Todo List"。
-
一个输入框,用户可以输入新的待办事项。
-
一个按钮,用于添加新的待办事项或更新正在编辑的事项。
-
一个无序列表(
ul),用于显示待办事项列表。- 我们使用
map函数遍历todos数组中的每个待办事项,并为每个事项渲染一个列表项(li)。 - 每个列表项包括待办事项文本、一个 "Edit" 按钮(用于编辑事项)和一个 "Delete" 按钮(用于删除事项)。
- 我们使用
-
-
我们使用
handleAddTodo函数来处理添加新的待办事项或更新正在编辑的事项。如果currentTodo不为空,我们将其添加到todos数组中(如果不在编辑模式),或者更新todos数组中正在编辑的事项。然后,我们清空currentTodo并将editingIndex重置为-1。 -
handleEditTodo函数用于在点击 "Edit" 按钮时将待办事项放入编辑模式。它将currentTodo设置为选定的待办事项文本,并将editingIndex设置为选定的索引。 -
handleDeleteTodo函数用于删除特定索引处的待办事项。我们通过过滤todos数组来删除选定的事项。 在这个示例中,我们创建了一个名为TodoList的函数组件,其中包含待办事项列表的相关逻辑。todos数组用于存储待办事项,currentTodo用于存储当前输入的待办事项,editingIndex用于跟踪正在编辑的待办事项的索引。
在界面上,我们展示了一个输入框、一个添加/更新按钮以及一个待办事项列表。每个待办事项旁边都有编辑和删除按钮,分别用于编辑和删除相应的事项。