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

如何在检测到移动设备时折叠shinydashboard::box组件

解决Shinydashboard Box根据设备类型自动折叠/展开的问题

你的核心错误是**collapsed参数需要布尔值(TRUE/FALSE),但你传递了textOutput这个UI组件**,类型不匹配导致报错。下面提供两种可行解决方案:

方法一:动态生成Box(推荐)

通过renderUI在服务器端根据设备类型动态生成Box,直接传递正确的布尔值给collapsed参数:

library(shiny)
library(shinybrowser)
library(shinydashboard)
library(shinyWidgets)

ui <- fluidPage(
  shinybrowser::detect(),
  shinyWidgets::useShinydashboard(),
  br(),
  # 用uiOutput占位,后续动态生成Box
  uiOutput("dynamic_box")
)

server <- function(input, output, session) {
  # 响应式获取当前设备类型
  device_type <- reactive({
    shinybrowser::get_device()
  })
  
  # 动态渲染Box
  output$dynamic_box <- renderUI({
    shinydashboard::box(
      title = "This is a box",
      width = 4,
      status = "success",
      solidHeader = TRUE,
      collapsible = TRUE,
      # 移动端折叠,桌面端展开
      collapsed = device_type() == "MOBILE",
      "collapse when mobile, expand when desktop"
    )
  })
  
  # 可选:控制台打印设备类型用于调试
  observe({
    print(device_type())
  })
}

shinyApp(ui, server)

方法二:用ShinyJS控制DOM状态

如果不想重新生成Box(比如Box内有复杂交互组件),可以用shinyjs直接操作DOM,修改Box的折叠类并触发状态切换:

library(shiny)
library(shinybrowser)
library(shinydashboard)
library(shinyWidgets)
library(shinyjs)

ui <- fluidPage(
  shinybrowser::detect(),
  shinyWidgets::useShinydashboard(),
  # 加载shinyjs
  shinyjs::useShinyjs(),
  br(),
  shinydashboard::box(
    # 给Box添加ID,方便定位
    id = "target_box",
    title = "This is a box",
    width = 4,
    status = "success",
    solidHeader = TRUE,
    collapsible = TRUE,
    collapsed = FALSE, # 初始状态设为展开
    "collapse when mobile, expand when desktop"
  )
)

server <- function(input, output, session) {
  observe({
    device <- shinybrowser::get_device()
    print(device)
    
    if (device == "MOBILE") {
      # 添加折叠类并模拟点击折叠按钮,确保状态生效
      shinyjs::addClass(id = "target_box", class = "collapsed-box")
      shinyjs::runjs("$('#target_box .btn-box-tool').click();")
    } else {
      # 移除折叠类,若当前是折叠状态则展开
      shinyjs::removeClass(id = "target_box", class = "collapsed-box")
      shinyjs::runjs("if ($('#target_box').hasClass('collapsed-box')) $('#target_box .btn-box-tool').click();")
    }
  })
}

shinyApp(ui, server)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:39:20