模块化Shiny应用:点击actionButton后隐藏初始文本问题排查
Shiny模块化应用文本无法隐藏的修复方案
问题原因
- 模块返回值格式错误:sideServer模块未以列表形式返回reactive对象,导致主server无法正确接收按钮点击信号
- shinyjs命名空间重复应用:textServer中对目标元素id重复使用命名空间函数,导致shinyjs找不到对应DOM元素
修改后的代码
app.R(无需修改)
library(shiny) library(shinyjs) library(shinydashboard) library(shinyWidgets) library(dplyr) # Load the modules source("sideUI.R") source("sideServer.R") source("textUI.R") source("textServer.R") # Build UI & server and then run the app ui <- dashboardPage( dashboardHeader(title = "Text Hiding Example"), dashboardSidebar(sideUI("side")), # Sidebar with the action button dashboardBody( useShinyjs(), # Initialize shinyjs textUI("textPL") # Text UI module ) ) server <- function(input, output, session) { # Use the reactive in another module btn_input <- sideServer("side") textServer("textPL", btn = btn_input$btn) } shinyApp(ui, server)
textUI.R(无需修改)
textUI <- function(id) { ns <- NS(id) tagList( div( id = ns("showtext"), p("This text will be hidden after clicking the button", style = "font-size: 16px; text-align: center;") ) ) }
textServer.R(修改shinyjs调用部分)
textServer <- function(id, btn) { moduleServer( id, function(input, output, session) { # Observe button click event observeEvent(btn(), { shinyjs::hide("showtext") # 直接使用模块内id,无需再次添加命名空间 }) } ) }
sideUI.R(无需修改)
sideUI <- function(id) { ns <- NS(id) tagList( actionButton(ns("action"), "Hide Text") ) }
sideServer.R(修改返回值格式)
sideServer <- function(id) { moduleServer( id, function(input, output, session) { return(list(btn = reactive(input$action))) # 以列表形式返回reactive对象 } ) }
说明
- 在Shiny模块的server逻辑中使用shinyjs时,直接使用模块内定义的原始id即可,
moduleServer的session会自动处理命名空间映射,无需额外调用ns()函数 - 模块间传递reactive对象时,建议以列表形式返回,保证主server能正确解构获取对应的值
内容的提问来源于stack exchange,提问作者firmo23
相关产品推荐
相关产品推荐

