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

求助:spsComps gallery在Shiny模态框中仅首次可放大的问题修复

Shiny模态框中spsComps::gallery组件放大功能二次打开失效的解决办法

问题原因

spsComps的gallery组件放大功能依赖页面加载时绑定的JavaScript事件。当模态框关闭后,模态框内的DOM元素会被移除,对应的事件绑定也随之消失;再次打开模态框时,新生成的gallery组件不会自动重新触发JavaScript事件初始化,导致放大功能失效。


解决方案1:提前渲染gallery组件(推荐)

将gallery组件提前放在UI的隐藏容器中,打开模态框时直接复用已初始化好的组件,避免事件绑定丢失。

library(shiny)
library(spsComps)

ui <- fluidPage(
  actionButton("modal", "Open modal"),
  # 提前渲染gallery并隐藏
  div(
    id = "pre_rendered_gallery",
    style = "display: none;",
    fluidRow(gallery(
      texts = "Click to enlarge", hrefs = "", image_frame_size = 6, 
      images = "https://cdn.pixabay.com/photo/2018/07/31/22/08/lion-3576045__340.jpg",
      enlarge = TRUE, title = "Enlargement works every time now",
      enlarge_method = "modal"
    ))
  )
)

server <- function(input, output, session) {
  
  observeEvent(input$modal, {
    showModal(modalDialog(
      title = "test",
      # 复用提前渲染的gallery
      uiOutput("gallery_content"),
      footer = modalButton("Cerrar"),
      easyClose = TRUE,
      size = "xl"
    ))
  })
  
  output$gallery_content <- renderUI({
    # 克隆已存在的gallery元素,避免直接移动DOM导致的问题
    htmltools::htmlClone(
      document.getElementById("pre_rendered_gallery")$children[[1]]
    )
  })
  
}

shinyApp(ui, server)

解决方案2:动态渲染时强制重新加载组件依赖

每次打开模态框时,手动附加gallery组件的JavaScript依赖,确保事件重新绑定。

library(shiny)
library(spsComps)
library(htmltools)

ui <- fluidPage(
  actionButton("modal", "Open modal")
)

server <- function(input, output, session) {
  
  observeEvent(input$modal, {
    # 创建gallery组件
    gallery_comp <- fluidRow(gallery(
      texts = "Click to enlarge", hrefs = "", image_frame_size = 6, 
      images = "https://cdn.pixabay.com/photo/2018/07/31/22/08/lion-3576045__340.jpg",
      enlarge = TRUE, title = "Enlargement works on re-open now",
      enlarge_method = "modal"
    ))
    # 获取组件的JavaScript依赖
    gallery_dependencies <- findDependencies(gallery_comp)
    
    showModal(modalDialog(
      title = "test",
      # 渲染组件并附加依赖
      tagList(gallery_comp, tagList(gallery_dependencies)),
      footer = modalButton("Cerrar"),
      easyClose = TRUE,
      size = "xl"
    ))
  })
  
}

shinyApp(ui, server)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:05:22