使用React函数组件,你写个todo-list要多久?

101 阅读1分钟

最近有些面试需要手写todo-list 那么接下来我们来看下是如何书写的 也给一些即将秋招的同学们一些想法。

TodoList.jsx

import React, { useState } from 'react';

function ToDoList() {
  const [tasks, setTasks] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [editIndex, setEditIndex] = useState(-1);

  const addTask = () => {
    if (inputValue) {
      if (editIndex === -1) {
        // 添加任务
        setTasks([...tasks, inputValue]);
      } else {
        // 修改任务
        const updatedTasks = [...tasks];
        updatedTasks[editIndex] = inputValue;
        setTasks(updatedTasks);
        setEditIndex(-1);
      }
      setInputValue('');
    }
  };

  const deleteTask = (index) => {
    const updatedTasks = [...tasks];
    updatedTasks.splice(index, 1);
    setTasks(updatedTasks);
  };

  const editTask = (index) => {
    const taskToEdit = tasks[index];
    setInputValue(taskToEdit);
    setEditIndex(index);
  };

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <button onClick={addTask}>{editIndex === -1 ? 'Add Task' : 'Update Task'}</button>
      <ul>
        {tasks.map((task, index) => (
          <li key={index}>
            {task}
            <button onClick={() => deleteTask(index)}>Delete</button>
            <button onClick={() => editTask(index)}>Edit</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default ToDoList;