如何在 React 中创建确认删除弹出窗口?

How to create a confirmation delete popup in React?

我正在创建一个 Todo 应用程序,并尝试创建一个 确认删除弹出窗口,它将在用户需要时显示删除待办事项。

在我的 todo.js 组件中,我创建了一个 onClick 回调,handleDelete,在我的删除按钮中,该回调会将弹出窗口设置为 true 使其可见,问题是在我的 handleDelete 中,我将 Id 作为参数传递,因此我可以跟踪已单击哪个待办事项并对其进行过滤以显示更新待办事项状态的新数据,但我只想更新数据当用户单击弹出窗口中的确认按钮时。

应用组件:

function App() {
  const [inputValue, setInputValue] = useState("");
  const [todos, setToDos] = useState([]);
  const [noToDo, setNoToDo] = useState(false);
  const [popup, setPopup] = useState(false);

  const handleOnSubmit = (e) => {
    e.preventDefault();

    setNoToDo(false);
    const ide = nanoid();
    const date = new Date().toISOString().slice(0, 10);
    const newToDo = { task: inputValue, id: ide, date: date };
    setToDos([...todos, newToDo]);
    setInputValue("");
  };

  const handleDelete = (id) => {
    setPopup(true);

    let filteredData = todos.filter((todo) => todo.id !== id);

    {
      /*
    filteredData is the new data, but I only want to update 
    todos with filteredData when the user has clicked on the confirm
    button in the modal component, which execute(handleDeleteTrue)*/
    }
  };

  const handleDeleteTrue = () => {
    setPopup(false);
    setToDos(filteredData);
  };

  const handleEdit = (id, task) => {
    setInputValue(task);
    const EditedData = todos.filter((edited) => edited.id !== id);
    setToDos(EditedData);
  };

  return (
    <div className="App">
      <div className="app_one">
        <h1>To do app</h1>
        <form action="" className="form" onSubmit={handleOnSubmit}>
          <input
            type="text"
            placeholder="Go to the park..."
            onChange={(e) => setInputValue(e.target.value)}
            value={inputValue}
          />
          <button type="submit">ADD TO DO</button>
        </form>
      </div>
      {noToDo && <FirstLoad />}
      {todos.map((todo) => {
        return (
          <div key={todo.id} className="result">
            <Todo
              {...todo}
              handleDelete={handleDelete}
              handleEdit={handleEdit}
            />
          </div>
        );
      })}
      {popup && <Popup handleDeleteTrue={handleDeleteTrue} />}
    </div>
  );
}

export default App;

待办组件:

const Todo = ({ handleDelete, handleEdit, task, id, date }) => {
  return (
    <>
      <div className="result_text">
        <h3>{task}</h3>
        <p className="result_textP">{date}</p>
      </div>
      <div>
        <button onClick={() => handleEdit(id, task)} className="button green">
          Edit
        </button>
        <button onClick={() => handleDelete(id)} className="button">
          delete
        </button>
      </div>
    </>
  );
};

export default Todo;

模态组件:

function Popup({ handleDeleteTrue }) {
  return (
    <div className="modal">
      <div className="modal_box">
        <p>You sure you wanna delete?</p>
        <button className="modal_buttonCancel">Cancel</button>
        <button onClick={handleDeleteTrue} className="modal_buttoDelete">
          Confirm
        </button>
      </div>
    </div>
  );
}

export default Popup;

我试图将 filteredData 声明为 global 变量,在我的 App 组件之外,所以当我执行 handleDelete 时它会初始化该变量使用过滤后的数据,只有当用户单击弹出窗口上的确认按钮时,它才会执行新函数 handleDeleteTrue,将数据更新为 filteredData.

它有效,但在我的组件外部声明变量不是一个好的做法,所以有没有更好的方法?

您当前代码中的问题是,您丢失应该删除的id,所以您需要将其存储在 refstate.

这是一个 解决方案,它将 id 与 shows/hides 确认框的布尔标志一起存储在状态中:

const [popup, setPopup] = useState({
  show: false, // initial values set to false and null
  id: null,
});

将删除处理程序修改为:

// This will show the Cofirmation Box

const handleDelete = (id) => {
  setPopup({
    show: true,
    id,
  });
};

// This will perform the deletion and hide the Confirmation Box

const handleDeleteTrue = () => {
  if (popup.show && popup.id) {
    let filteredData = todos.filter((todo) => todo.id !== popup.id);
    setToDos(filteredData);
    setPopup({
      show: false,
      id: null,
    });
  }
};

// This will just hide the Confirmation Box when user clicks "No"/"Cancel"

const handleDeleteFalse = () => {
  setPopup({
    show: false,
    id: null,
  });
};

然后,在 JSX 中,将处理程序传递给 Popup:

{popup.show && (
  <Popup
    handleDeleteTrue={handleDeleteTrue}
    handleDeleteFalse={handleDeleteFalse}
  />
)}