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

模块化Shiny应用:点击actionButton后隐藏初始文本问题排查

Shiny模块化应用文本无法隐藏的修复方案

问题原因

  1. 模块返回值格式错误:sideServer模块未以列表形式返回reactive对象,导致主server无法正确接收按钮点击信号
  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 20:32:37