shinyWidgets中ask_confirmation的callbackJS参数不生效如何修复?
问题根因
shinyWidgets::ask_confirmation() 本身不存在callbackJS参数,你直接套用shinyalert的参数名,写的JS回调代码会被函数直接忽略,自然无法生效。
这个函数的设计逻辑是:用户对弹窗的所有操作结果,都会自动传回Shiny服务端,存储在input$<弹窗ID>对应的输入对象里,不需要额外写前端回调就能判断点击行为。
修复方法
优先用Shiny原生方式处理,不需要写自定义JS,逻辑更稳定:
- 你定义的弹窗ID是
form1,操作返回值规则如下:- 点击OK按钮:返回
TRUE - 点击Cancel按钮、按ESC键、点击弹窗外部关闭:返回
FALSE
- 点击OK按钮:返回
- 直接在服务端用
observeEvent监听input$form1即可,修复后的完整可运行代码:
library(shiny) library(shinyWidgets) ui <- fluidPage( ) server <- function(input, output, session) { ask_confirmation( inputId = "form1", title = " ", type = "question", btn_labels = c("Cancel", "OK"), allowEscapeKey = TRUE, closeOnClickOutside = TRUE, html = TRUE, text = div(HTML(" <form style='display:flex; flex-direction: row; justify-content: center; align-items: center' action=''> <div style='border: 5px black;'> <input type='text' name='add_nosha_tohen' autocomplete='off' id='add_nosha_tohen' value='' dir='rtl' style='border-color: black; font-size: 12px;height: 45px; width: 400px; display: block;'/> </div> </form> " )) ) # 监听弹窗点击结果 observeEvent(input$form1, { if (isTRUE(input$form1)) { # 此处写点击OK后要执行的逻辑,比如读取输入框内容、触发后续流程 print("用户点击OK") # 读取自定义输入框的值直接用input$add_nosha_tohen即可 } else { # 此处写点击Cancel/关闭弹窗后要执行的逻辑 print("用户取消/关闭弹窗") } }, once = TRUE) } shinyApp(ui, server)
注意事项
- 原代码里的
</input>是冗余写法,input是自闭合标签,不需要额外加闭合标签,否则可能出现渲染异常,上面的代码已经删掉了这部分。 - 如果确实需要前端执行JS回调,不能直接传
callbackJS,需要通过options参数传入SweetAlert2原生支持的回调配置,这种方式调试成本高,非必要不推荐。
内容的提问来源于stack exchange,提问作者asdf1212
相关产品推荐
相关产品推荐

