从确认警报功能获取 return 值,以便我可以将 setEditclicked 设置为 false

getting return value from confirm alert function so that i can setEditclicked to false

我有一个确认功能,它要求通过 react-confirm-alert 进行确认。如果用户单击“是”或“否”,我需要从此函数得到一些回复,以便我可以将 editClicked 设置为 false。以下是我的代码。

const handleClickUpdate = () => {
if (previousValue !== post)
  editPost(post, postId, "original")
    .then(() => setEditClicked(false))
    .catch(() => {
      confirm("edit", post, postId, editPost);
    });
 };




import { confirmAlert } from "react-confirm-alert";
export const confirm = (id, arg1, arg2, cb) => {
let title, message;

if (id === "delete") {
title = "Are you sure you want to delete this post";
message = "click yes to proceed";
} else {
title = "This post title already exists";
message = "Do you still want to continue";
}

confirmAlert({
title: title,
message: message,
buttons: [
  {
    label: "Yes",
    onClick: () => {
      id === "delete" ? cb(arg1, arg2) : cb(arg1, arg2, "duplicate");
    },
  },
  {
    label: "No",
    onClick: () => "no",
  },
],
});
};

编辑:

  1. 我需要 confirm 函数来 return 返回一些值,以便处理点击更新可以根据用户的点击将编辑点击的状态设置为 true 或 false。如果用户点击是,状态将为假,反之亦然

  2. onClick: () => "no",假设如果没有被点击,有没有办法return一个值,这样调用确认函数的处理点击更新就会知道没有被点击点击了吗?

我想你可以传递一个取消回调来调用并传回一个值。我在这里称它为 cb2“回调 2”。

const confirm = (id, arg1, arg2, cb, cb2) => {
  let title, message;

  if (id === "delete") {
    title = "Are you sure you want to delete this post";
    message = "click yes to proceed";
  } else {
    title = "This post title already exists";
    message = "Do you still want to continue";
  }

  confirmAlert({
    title: title,
    message: message,
    buttons: [
      {
        label: "Yes",
        onClick: () => {
          id === "delete" ? cb(arg1, arg2) : cb(arg1, arg2, "duplicate");
        }
      },
      {
        label: "No",
        onClick: () => cb2("no") // <-- pass cancel value back out.
      }
    ]
  });
};

用法示例:

<button
  type="button"
  onClick={() =>
    confirm(
      "test",
      0,
      1,
      (...args) => console.log("confirmed", args),
      (value) => console.log("declined", value)
    )
  }
>
  Open Confirm
</button>

更具体的例子:

confirm("edit", post, postId, editPost, cancelEditPost);