首页 > 解决方案 > shinyjs:当条件不评估为 TRUE 时,切换不会隐藏自定义 UI

问题描述

我正在使用shinyjspkg 和各种隐藏/显示自定义 UI 的选项。在下面的应用程序中,我想显示选定的图,如果未选择任何选项,则显示一个空白区域。我使用toggle(),只要选择了至少一个选项,它就可以解决问题checkboxGroupInput,但是当没有选择任何选项时,两个图都会显示。根据文件

如果给定条件来切换,则该条件将用于确定是显示还是隐藏元素。如果条件评估为 TRUE,则将显示该元素,否则将隐藏该元素。

我在这里遗漏了一些明显的东西吗?

library(shiny)
library(shinyjs)
library(ggplot2)

ui <-dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    useShinyjs(),
    checkboxGroupInput(inputId = 'options',
                       label = 'Choose your plot(s)',
                       choices = list("Plot 1" = 1,
                                      "Plot2" = 2)),
                       #selected = 1:2),
    verbatimTextOutput('checkbox_text'),
        uiOutput("Ui1"),
        uiOutput('Ui2')
        )
)

server <- function(input, output, session) {

  output$checkbox_text <- renderText({
    paste(input$options)
  })


    observe({
    shinyjs::toggle(id = "Ui1", condition = input$options == 1)
    shinyjs::toggle(id = "Ui2", condition = input$options == 2)
  })

  output$Ui1 <- renderUI({

    output$plot1 <- renderPlot({
      p <- ggplot(mtcars, aes(disp, mpg)) +
        geom_point() +
        geom_smooth() +
        ggtitle('Plot 1')
      p  
    })

    plotOutput('plot1')
  })

  output$Ui2 <- renderUI({

    output$plot2 <- renderPlot({
      p<- ggplot(mtcars, aes(disp, mpg, colour = as.factor(cyl))) +
        geom_point() +
        ggtitle('Plot 2')
      p
    })

    plotOutput('plot2')
  })

}

shinyApp(ui, server)

标签: rshinytoggleshinydashboardshinyjs

解决方案


当您正在寻找选中哪些框时checkboxGroupInput,通常最好评估您感兴趣的值是否等于其中的任何值checkboxGroupInput- 用此替换您的observe语句将解决问题:

  observe({
    shinyjs::toggle(id = "Ui1", condition = {1 %in% input$options})
    shinyjs::toggle(id = "Ui2", condition = {2 %in% input$options})
  })

就是说,我不确定为什么TRUE在您的情况下没有选中任何一个框都会评估为。


推荐阅读