删除图标,该图标显示或隐藏Shinydashboard中某个特定选项卡的左侧边栏

时间:2020-03-27 23:32:56

标签: r shiny shinydashboard

我下面有一个发光的仪表板,我想在其中隐藏标题左侧的图标,如果按下该图标,它将隐藏或显示左侧边栏。只有在“前”标签中的Im时才可以隐藏它吗?

enter image description here

# app.R ##
library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(DT)
library(shinyWidgets)
library(shinyjs)

dbHeader <- dashboardHeaderPlus(
                            enable_rightsidebar = TRUE,
                            rightSidebarIcon = "gears",
                            fixed = T
                            )

ui <- dashboardPagePlus(
  dbHeader,
  dashboardSidebar(),
  dashboardBody(
    useShinyjs(),
    tags$hr(),
    tabsetPanel(
      id ="tabA",
      type = "tabs",
      tabPanel("Front",icon = icon("accusoft")),
      tabPanel("Data", icon = icon("table")
      )
    )
  ),
  rightsidebar = rightSidebar()
)

server <- function(input, output) {
  observe({
    if (input$tabA == "Front") {
      hide(selector = "body > div.wrapper > header > nav > div:nth-child(4) > ul")
      addClass(selector = "body", class = "sidebar-collapse")
      removeClass(selector = "body", class = "control-sidebar-open")
    } else {
      show(selector = "body > div.wrapper > header > nav > div:nth-child(4) > ul")
      removeClass(selector = "body", class = "sidebar-collapse")
      addClass(selector = "body", class = "control-sidebar-open")
    }
  })
}

shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:2)

如果只想隐藏图标,则可以借助一些Javascript代码来完成。为了将JS代码插入Shiny,必须使用tags$script()

因此,为了隐藏图标,请在dashboardBody()内的下面的代码中插入

   # Note: 'sidebar-toggle' is a class name (i.e. HTML class attribute) of Shiny icon 
   tags$script("document.getElementsByClassName('sidebar-toggle')[0].style.visibility = 'hidden';"),

输出为: enter image description here

有关在Shiny中插入JS的更多信息,请参见:https://shiny.rstudio.com/articles/packaging-javascript.html

已更新

如果您只想在用户位于“前”标签中时隐藏图标,则可以通过插入一些JS代码来再次执行此操作,但是这次您可以将其插入服务器端部分(即{{1 }}函数)。

因此,您需要插入JS部分,如果按下“ Front”选项卡,它将隐藏图标

observe

如果按下标签“数据”,将显示图标的部分

  shinyjs::runjs("document.getElementsByClassName('sidebar-toggle')[0].style.visibility = 'hidden';")

所以您的整个代码看起来像这样

  shinyjs::runjs("document.getElementsByClassName('sidebar-toggle')[0].style.visibility = 'visible';")