javascript - 如何为我的 ToDo List 应用程序创建一个编辑选项?
问题描述
我是 React 新手,我一直在使用 State Hooks 制作一个简单的待办事项列表。我无法为其创建编辑选项。当我按下“编辑按钮”时,我想去任务并修改它,但我完全一无所知。
这是按钮所在的位置:
import React from 'react';
function TodoList({ todo, index, toggleComplete, removeTodo, editTodo}) {
function Checkbox() {
toggleComplete(todo.index);
}
return (
<div className="todo">
<input type = "checkbox" onClick={Checkbox}/>
<div style={{textDecoration: todo.completed ? "line-through" : "" }} >
{todo.text}
</div>
<div>
<button class = "button" onClick={() => editTodo(todo.text, todo.index)}>Edit Task</button>
<button class = "button" onClick={() => removeTodo(index)}>Delete Task</button>
</div>
</div>
);
}
export default TodoList;
这是 App.js 的一部分,带有我损坏的 editTodo 函数:
function App() {
const [todos, setTodos] = useState([]);
const editTodo = (text, index) => {
setTodos(
todos.map(todo => {
if(todo.index === index){
console.log(todo.text);
todo.text = text;
console.log(todo.text);
};
return todo;
}))
}
return (
<div className="App">
<div className="todo-list">
<h3 class="title is-3" style={{textAlign: "center"}}>To-do list</h3>
<TodoForm addTodo={addTodo} clearList={clearList} />
{todos.map((todo, index) => (
<TodoList
key = {index}
index = {index}
todo = {todo}
toggleComplete = {toggleComplete}
removeTodo = {removeTodo}
editTodo = {editTodo}
/>
))}
</div>
</div>
);
}
export default App;
解决方案
好吧,您已经完成了大部分工作,只剩下更改状态了。
正如您已经使用过的map
那样,我会建议像这样
注意:我假设你的 todo 对象看起来像这样
{
index: 1
text: "string"
}
const editTodo = (text, index) => {
setTodos(
todos.map(todo => {
if(todo.index === index){
return {...todo, text}
};
return todo;
}))
}
推荐阅读
- java - 是否可以将 pushID 绑定到 Firebase 数据库中的 userUid
- c++ - c++ *(Type*) 属性名
- python - 如何在 jupyter notebbok 中访问内核变量
- android - Android:更改联系人时,带有广播接收器的前台服务停止工作
- c++ - 对象是 C++ 中的存储位置还是值?
- node.js - 我可以使用“AND”来连接或创建棱镜的位置吗?
- jquery - JQuery 每个输入函数都停在最后一个元素而不是前一个元素
- python - 如何为在同一台机器上运行的客户端和服务器设置不同的 IP?
- php - 记录更新、事务死锁
- reactjs - 如何在 ComposedChart 中绘制多条带有偏移的线?