如何使用shinyjs隐藏/显示shinyWidgets的dropdown组件?
用shinyjs控制shinyWidgets dropdown组件的显示/隐藏
问题出在shinyWidgets的dropdown组件渲染后,你指定的inputId = "dropdown"对应的并不是下拉面板的外层DOM元素,而是组件内部用于记录状态的隐藏输入框,所以直接用shinyjs::show("dropdown")只会操作那个隐藏元素,不会影响下拉面板的显示。
下面是两种可行的解决方法:
方法一:给dropdown套一个容器,控制容器的显示/隐藏
把dropdown放在一个带id的div里,用shinyjs控制这个容器的显示和隐藏,这种方式简单且可靠:
library(shiny) library(shinyjs) library(shinyWidgets) ui <- fluidPage( useShinyjs(), titlePanel("Old Faithful Geyser Data"), sidebarLayout( sidebarPanel( # 给dropdown套一个带id的div,初始隐藏 hidden( div(id = "dropdown_container", dropdown(inputId = "dropdown", sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30) ) ) ) ), mainPanel( actionButton("showdd", "show dropdown"), plotOutput("distPlot") ) ) ) server <- function(input, output) { observeEvent(input$showdd,{ show(id = "dropdown_container") }) output$distPlot <- renderPlot({ x <- faithful[, 2] bins <- seq(min(x), max(x), length.out = input$bins + 1) hist(x, breaks = bins, col = 'darkgray', border = 'white', xlab = 'Waiting time to next eruption (in mins)', main = 'Histogram of waiting times') }) } shinyApp(ui = ui, server = server)
方法二:直接操作dropdown的DOM元素
shinyWidgets的dropdown组件渲染后,触发按钮的类是.dropdown-toggle,下拉面板的类是.dropdown-menu,它们的父元素id为dropdown-[你的inputId](这里就是dropdown-dropdown)。可以用shinyjs的runjs来操作这些元素的显示状态:
library(shiny) library(shinyjs) library(shinyWidgets) ui <- fluidPage( useShinyjs(), titlePanel("Old Faithful Geyser Data"), sidebarLayout( sidebarPanel( # 初始隐藏dropdown的触发按钮和面板 tags$script(HTML(" $(document).ready(function() { $('#dropdown-dropdown .dropdown-toggle').hide(); $('#dropdown-dropdown .dropdown-menu').hide(); }); ")), dropdown(inputId = "dropdown", sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30) ) ), mainPanel( actionButton("showdd", "show dropdown"), plotOutput("distPlot") ) ) ) server <- function(input, output) { observeEvent(input$showdd,{ runjs(" $('#dropdown-dropdown .dropdown-toggle').show(); $('#dropdown-dropdown .dropdown-menu').show(); ") }) output$distPlot <- renderPlot({ x <- faithful[, 2] bins <- seq(min(x), max(x), length.out = input$bins + 1) hist(x, breaks = bins, col = 'darkgray', border = 'white', xlab = 'Waiting time to next eruption (in mins)', main = 'Histogram of waiting times') }) } shinyApp(ui = ui, server = server)
第一种方法更推荐,因为不需要依赖组件内部的DOM结构,后续组件版本更新也不容易失效。
内容的提问来源于stack exchange,提问作者Helbisch
相关产品推荐
相关产品推荐

