R Shiny中嵌入{daff}HTML输出时action button仅单次生效问题
问题原因
daff::render_diff默认输出包含<html>、<head>、<body>等根标签的完整HTML文档,直接插入Shiny页面后会破坏原有DOM结构,导致Shiny的事件绑定失效,因此第一次弹出模态框后,后续点击保存按钮无响应- 模态框仅展示文本或普通表格时,不存在完整HTML结构冲突,因此功能可正常运行
修复后完整可运行代码
仅需裁剪daff输出的内容,仅保留对比表格的核心片段即可解决冲突:
library(shinydashboard) library(daff) library(dplyr) library(DataEditR) df1 = iris %>% slice(1:10) %>% select(-Species) df2 = iris %>% slice(1:12) # Define UI ui = shinyUI( fluidPage( fluidRow( box( title = "First data", status = "success", width = 6, solidHeader = TRUE, collapsible = TRUE, dataEditUI(id = "old_data") ), box( title = "New data", status = "primary", width = 6, solidHeader = TRUE, collapsible = TRUE, dataEditUI(id = "new_data"), br(), actionButton("save", "Save!") ) ) ) ) # Define server server = shinyServer(function(input, output, session) { data_old = dataEditServer( "old_data", data = df1, col_readonly = names(df1), col_names = FALSE, col_options = TRUE, row_edit = FALSE ) data_new = dataEditServer( "new_data", data = df2, col_names = FALSE, col_options = TRUE, row_edit = FALSE ) diff_data = reactive({ full_html <- daff::render_diff( daff::diff_data( data_old(), data_new() ), view = FALSE ) # 仅提取body内的对比表格内容,丢弃外层完整HTML结构避免DOM冲突 gsub("^.*<body>(.*)</body>.*$", "\\1", full_html) }) output$compare_df = renderUI({ HTML( diff_data() ) }) observeEvent( input$save, { showModal( modalDialog( span( "Check modification before validation!", style = "color: red; font-size: 130%;" ), br(), br(), uiOutput("compare_df"), footer = tagList( modalButton("Cancel"), actionButton("ok", "OK") ), easyClose = TRUE, size = "l" ) ) } ) observeEvent( input$ok, { print(data_new()) removeModal() } ) }) shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者Mostafa90
相关产品推荐
相关产品推荐

