首页 > 解决方案 > 如何为我的 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;

标签: javascriptreactjsreact-hooks

解决方案


好吧,您已经完成了大部分工作,只剩下更改状态了。

正如您已经使用过的map那样,我会建议像这样

注意:我假设你的 todo 对象看起来像这样

{
  index: 1 
  text: "string"
}
const editTodo = (text, index) => {
    setTodos(
      todos.map(todo => {
        if(todo.index === index){
          return {...todo, text}
        };
        return todo;
      }))
  }

推荐阅读