You need to enable JavaScript to run this app. React项目中使用SweetAlert内嵌按钮点击无响应,是否存在语法错误?
优惠活动
大模型
产品
解决方案
定价
更多

React项目中使用SweetAlert内嵌按钮点击无响应,是否存在语法错误?

问题原因

这不是语法错误,核心问题是原版SweetAlert库不支持直接传入React JSX作为弹窗内容:你传入的JSX会被库直接转为纯HTML字符串渲染,React绑定的合成事件onClick会在转义过程中完全丢失,自然不会触发console.log(123)的逻辑。

解决方案

方案1:使用React适配的SweetAlert版本(推荐)

改用sweetalert2 + 官方React适配包sweetalert2-react-content,可以完美支持JSX内容和React事件绑定:

  1. 安装依赖
npm install sweetalert2 @sweetalert2/with-react-content
  1. 调用示例
import Swal from 'sweetalert2'
import withReactContent from '@sweetalert2/with-react-content'

// 生成支持React内容的Swal实例
const ReactSwal = withReactContent(Swal)

// 弹窗调用
ReactSwal.fire({
  html: (
    <div>
      <button 
        className='btn btn-danger' 
        onClick={() => console.log(123)}
      >
        confirm
      </button>
    </div>
  )
})

方案2:原生事件绑定(不换库的临时方案)

如果坚持使用旧版SweetAlert,可以放弃React合成事件,改用原生事件绑定:

swal({
  content: {
    element: "div",
    attributes: {
      innerHTML: `<button class='btn btn-danger' onclick="console.log(123)">confirm</button>`
    }
  }
})

如果需要调用React组件内部的方法,可以临时将方法挂载到window对象上,弹窗关闭后再销毁挂载的方法避免内存泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 16:27:10