【问题标题】:How to programmatically collapse a box in shiny dashboard如何以编程方式折叠闪亮仪表板中的框
【发布时间】:2015-11-13 07:24:50
【问题描述】:

我正在尝试在输入更改时以编程方式折叠框。看来我只需要将类"collapsed-box" 添加到盒子中,我尝试使用shinyjs 函数addClass,但我不知道该怎么做,因为盒子没有id。这里是简单的基本代码,可用于测试可能的解决方案:

library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
      box(collapsible = TRUE,p("Test")),
      actionButton("bt1", "Collapse")
  )
)

server <- function(input, output) {
  observeEvent(input$bt1, {
    # collapse the box
  })
}

shinyApp(ui, server)

【问题讨论】:

    标签: shiny shinydashboard shinyjs


    【解决方案1】:

    我以前从未尝试过使用盒子,所以请记住,我的回答可能非常狭隘。但我快速浏览了一下,看起来只是在盒子上设置“折叠盒”类实际上并没有使盒子折叠。因此,我的下一个想法是以编程方式实际单击折叠按钮。

    正如您所说,没有与该框关联的标识符,因此我的解决方案是向box 添加一个id 参数。我最初期望它是盒子的 id,但看起来这个 id 是给盒子内的一个元素的。没问题 - 这只是意味着为了选择折叠按钮,我们需要获取 id,查找 DOM 树找到 box 元素,然后再向下查找 DOM 树找到按钮。

    我希望我所说的一切都是有道理的。即使没有,这段代码应该仍然可以工作,并且希望能让事情变得更清楚:)

    library(shiny)
    library(shinydashboard)
    library(shinyjs)
    
    jscode <- "
    shinyjs.collapse = function(boxid) {
    $('#' + boxid).closest('.box').find('[data-widget=collapse]').click();
    }
    "
    
    ui <- dashboardPage(
      dashboardHeader(),
      dashboardSidebar(),
      dashboardBody(
        useShinyjs(),
        extendShinyjs(text = jscode),
        actionButton("bt1", "Collapse box1"),
        actionButton("bt2", "Collapse box2"),
        br(), br(),
        box(id = "box1", collapsible = TRUE, p("Box 1")),
        box(id = "box2", collapsible = TRUE, p("Box 2"))
      )
    )
    
    server <- function(input, output) {
      observeEvent(input$bt1, {
        js$collapse("box1")
      })
      observeEvent(input$bt2, {
        js$collapse("box2")
      })
    }
    
    shinyApp(ui, server)
    

    【讨论】:

    • 谢谢@daattali 它的工作原理!,也感谢你非常有用的shinyjs。
    • 我知道这是一篇很老的帖子,但我们必须使用dashboardPage 才能让它工作吗?我试过在 navbarPage 中使用它,但它不起作用。有什么解决方法吗?
    • @MridulGarg 无论如何它应该可以工作。检查您是否添加了useShinyjs()
    • 不确定这是否对任何人都有帮助,但如果您的 shinydashboard::box 在闪亮的模块中,那么您应该:(i) 在 UI 中使用 ns("box1") 设置框的 ID模块的函数和(ii)在模块的服务器函数中使用js$collapse(session$ns("box1"))
    猜你喜欢
    • 2021-09-05
    • 1970-01-01
    • 2020-05-10
    • 2018-01-09
    • 2018-09-25
    • 2015-04-22
    • 1970-01-01
    • 2016-01-11
    • 2018-05-30
    相关资源
    最近更新 更多