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

React项目中SweetAlert2无法显示3个按钮问题咨询

SweetAlert2 三按钮弹窗显示异常解决方案

问题根因

你使用的showDenyButtonAPI是SweetAlert2 v10.0.0及以上版本才支持的特性,当前项目存在三个兼容问题:

  1. 安装的sweetalert2-react-content v3.3.2对应的SweetAlert2核心包版本低于v10,不支持三按钮API
  2. 代码中已经通过withReactContent生成了适配React的MySwal实例,但实际调用时仍用了原生Swal对象,配置没有生效
  3. 项目中安装的sweetalert2-react包已经官方废弃,会和新的依赖产生冲突

解决方案

  • 第一步:卸载旧的不兼容依赖
    执行如下命令移除冲突包:
npm uninstall sweetalert2-react sweetalert2 sweetalert2-react-content
# 若使用yarn则执行:
# yarn remove sweetalert2-react sweetalert2 sweetalert2-react-content
  • 第二步:安装匹配的高版本依赖
npm install sweetalert2@^11.0.0 sweetalert2-react-content@^5.0.0
# 若使用yarn则执行:
# yarn add sweetalert2@^11.0.0 sweetalert2-react-content@^5.0.0
  • 第三步:修正代码调用逻辑
    修改后的完整可运行代码如下:
import Swal from 'sweetalert2';
import withReactContent from 'sweetalert2-react-content'

const HomeScreen = ({ navigation, route }) => 
{
  const MySwal = withReactContent(Swal);
  // 其他业务逻辑
  MySwal.fire({
    title: '是否保存修改?',
    showDenyButton: true,
    showCancelButton: true,
    confirmButtonText: `保存`,
    denyButtonText: `不保存`,
    cancelButtonText: `取消`
  }).then(function (result) {
    console.log(result)
    if (result.isConfirmed) {
      // 保存逻辑
    } else if (result.isDenied) {
      // 不保存逻辑
    } else if (result.isDismissed) {
      // 取消逻辑
    }
  })
  // 其他业务逻辑
}

可选配置

如果需要调整按钮显示顺序符合国内用户操作习惯,可以在配置中添加reverseButtons: false,按钮会按照「取消、不保存、保存」的顺序排列。

内容的提问来源于stack exchange,提问作者user15404864

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:42:02