如何为“待办事项列表”应用程序设置编辑选项?

时间:2020-06-11 09:02:08

标签: javascript reactjs react-hooks

我是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;

1 个答案:

答案 0 :(得分:0)

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

因为您已经使用过map,所以我建议使用这样的方式

注意:我认为您的待办事项对象看起来像这样

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