You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何让SweetAlert确认框无需Promise返回true/false值

解决SweetAlert确认弹窗返回值获取问题

你当前的封装代码仅在用户点击确认按钮时才触发回调,导致无法获取取消操作的返回状态。只需对封装函数做简单调整,就能让回调拿到两种操作的对应返回值:

修改后的封装代码

//DEFINE
function sweetConfirm(title, message, callback) {
  swal({
    title: title,
    text: message,
    buttons: true
  }).then((confirmed) => {
    // 无论确认还是取消,都把状态传给回调函数
    callback(confirmed);
  });
}
export default sweetConfirm;

使用示例

//USAGE
sweetConfirm('确认操作!', '你确定要执行此操作吗?', function (confirmed) {
  if (confirmed) {
    console.log("用户确认了操作");
  } else {
    console.log("用户取消了操作");
  }
});

修改说明

核心调整点:删掉原代码里仅在confirmed为true时调用callback的判断,改为在swal的then回调中直接将confirmed参数传递给自定义回调。这样用户点击确认时confirmed为true,点击取消时为false,回调就能根据这个值分别处理两种场景。

内容的提问来源于stack exchange,提问作者Shahidur Rahman Nayeem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 03:55:21