我正在尝试找到一种方法来检查 Shiny Dashboard Box 是折叠还是展开。
通过阅读@daattali 在 How to manually collapse a box in shiny dashboard 中的精彩回复我知道可以使用 shinyjs 包从服务器端折叠框,如下面的代码所示
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)
通过检查 UI HTML,我发现我的问题的答案可以通过访问图标类来解决(查看它是 fa fa-plus 还是 fa fa-minus),但我不知道该怎么做。
如有任何帮助,我们将不胜感激。
干杯
最佳答案
你可以创建一个新的输入,当用户折叠框时触发,像这样:
collapseInput <- function(inputId, boxId) {
tags$script(
sprintf(
"$('#%s').closest('.box').on('hidden.bs.collapse', function () {Shiny.onInputChange('%s', true);})",
boxId, inputId
),
sprintf(
"$('#%s').closest('.box').on('shown.bs.collapse', function () {Shiny.onInputChange('%s', false);})",
boxId, inputId
)
)
}
以你为例:
library(shiny)
library(shinydashboard)
library(shinyjs)
jscode <- "
shinyjs.collapse = function(boxid) {
$('#' + boxid).closest('.box').find('[data-widget=collapse]').click();
}
"
collapseInput <- function(inputId, boxId) {
tags$script(
sprintf(
"$('#%s').closest('.box').on('hidden.bs.collapse', function () {Shiny.onInputChange('%s', true);})",
boxId, inputId
),
sprintf(
"$('#%s').closest('.box').on('shown.bs.collapse', function () {Shiny.onInputChange('%s', false);})",
boxId, inputId
)
)
}
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")),
collapseInput(inputId = "iscollapsebox1", boxId = "box1"),
verbatimTextOutput(outputId = "res")
)
)
server <- function(input, output) {
observeEvent(input$bt1, {
js$collapse("box1")
})
observeEvent(input$bt2, {
js$collapse("box2")
})
output$res <- renderPrint({
input$iscollapsebox1
})
}
shinyApp(ui, server)
您可以在函数 中通过
。'collapse'
/'expanded'
更改 true
/false
如果需要,当它调用 Shiny.onInputChange
时 collapseInput
关于r - 如何从服务器端查看 Shiny 的仪表板框是否折叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45462614/