简体   繁体   中英

How to make an edit option for my ToDo List application?

I am new to React and I've been working on a simple To-do list with State Hooks. I am having trouble to make an edit option for it. When I am pushing the "Edit button" I want to go to the task and modify it, but I am completely clueless.

This is where the button is:

 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;

This is a part of App.js with my broken editTodo function:

 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;

Well You have done most of it, only changing the state remains.

As You have already used map I would suggest smth like this

Note: I assume that Your todo object looks like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM