如何使用React实现一个简单的待办事项 | 青训营

68 阅读1分钟

以下是一个简单的待办事项列表示例代码:

import React, { useState } from 'react';  
  
function TodoList() {  
  const [todos, setTodos] = useState([]);  
  const [inputValue, setInputValue] = useState('');  
  
  function handleAddTodo() {  
    if (inputValue.trim() === ''return;  
    setTodos([...todos, inputValue]);  
    setInputValue('');  
  }  
  
  function handleEditTodo(index, newValue) {  
    const newTodos = [...todos];  
    newTodos[index] = newValue;  
    setTodos(newTodos);  
  }  
  
  function handleDeleteTodo(index) {  
    const newTodos = [...todos];  
    newTodos.splice(index, 1);  
    setTodos(newTodos);  
  }  
  
  return (  
    <div>  
      <h1>Todo List</h1>  
      <input  
        type="text"  
        value={inputValue}  
        onChange={(e) => setInputValue(e.target.value)}  
      />  
      <button onClick={handleAddTodo}>Add</button>  
      <ul>  
        {todos.map((todo, index) => (  
          <li key={index}>  
            <input  
              type="text"  
              value={todo}  
              onChange={(e) => handleEditTodo(index, e.target.value)}  
            />  
            <button onClick={() => handleDeleteTodo(index)}>Delete</button>  
          </li>  
        ))}  
      </ul>  
    </div>  
  );  
}  
  
export default TodoList;  

这个组件使用了React的Hooks API来管理状态。它有一个todos数组来存储所有待办事项,以及一个inputValue字符串来存储用户输入的值。

当用户点击"Add"按钮时,我们会将inputValue添加到todos数组中,并清空inputValue

当用户编辑一个待办事项时,我们会通过handleEditTodo函数来更新todos数组中的相应项。

当用户删除一个待办事项时,我们会通过handleDeleteTodo函数来从todos数组中删除相应项。

最后,我们将所有待办事项呈现为一个无序列表,并为每个项目提供一个编辑和删除按钮。