首页 > 解决方案 > 隐藏和清除 selectInput

问题描述

我需要显示\隐藏输入,如果输入不存在,我会得到 NULL 或空字符串,这里是可重现的例子:

ui <- 
  dashboardPage(
    dashboardHeader(
      title = 'Test'),
    dashboardSidebar(),
    dashboardBody(
      selectInput(
        inputId = 'mainInput',
        label = 'Main input',
        selected = 'Show',
        choices = c('Show', 'Hide')
      ),
      uiOutput(
        outputId = 'secondInputUI'
      ),
      actionButton(
        inputId = 'thirdInput',
        label = 'Check value'
      )
    )
)
server <- function(input, output, session){
  observeEvent(input$mainInput, ignoreNULL = TRUE, {
    if (input$mainInput == 'Show')
      output$secondInputUI <- 
        renderUI(
          selectInput(
            inputId = 'secondInput',
            label = 'Second input',
            selected = 0,
            multiple = FALSE,
            choices = c(1, 0)
          )
        )
    else {
      output$secondInputUI <- 
        renderUI(
          selectInput(
            inputId = 'secondInput',
            label = 'Second input',
            selected = '',
            multiple = TRUE,
            choices = c(1, 0)
          )
        )
      # If uncommit - input value don't update and will return latest available before delete input
      # output$secondInputUI <- 
      #   NULL
    }
  })

  observeEvent(input$thirdInput, {
    showNotification(
      session = session, 
      ui = paste(input$secondInput, collapse = ', '))
  })
}

shinyApp(
  ui = ui,
  server = server)

您可以看到将 NULL 设置为 uioutput 的注释部分,如果它处于活动状态 - 在清除该 ui 之前闪亮返回最新的可用值,那么如何处理呢?

标签: rshinyshinydashboardshiny-reactivity

解决方案


我觉得我懂了。您可以创建一个独立于 UI 的反应变量,因为当 UI 元素被移除时输入不会更新。

library(shiny)
library(shinydashboard)

ui <- 
  dashboardPage(
    dashboardHeader(
      title = 'Test'),
    dashboardSidebar(),
    dashboardBody(
      selectInput(
        inputId = 'mainInput',
        label = 'Main input',
        selected = 'Show',
        choices = c('Show', 'Hide')
      ),
      uiOutput(
        outputId = 'secondInputUI'
      ),
      actionButton(
        inputId = 'thirdInput',
        label = 'Check value'
      )
    )
  )
server <- function(input, output, session){

  secondInputVar <- reactive({
    if(input$mainInput == 'Show'){
      input$secondInput
    } else {

    }
  })

  observeEvent(input$mainInput, ignoreNULL = TRUE, {
    if (input$mainInput == 'Show')
      output$secondInputUI <- 
        renderUI(
          selectInput(
            inputId = 'secondInput',
            label = 'Second input',
            selected = 0,
            multiple = FALSE,
            choices = c(1, 0)
          )
        )
    else {
      output$secondInputUI <- renderUI({
        NULL
      })
    }
  })

  observeEvent(input$thirdInput, {
    showNotification(
      session = session, 
      ui = paste(secondInputVar(), collapse = ', '))
  })
}

shinyApp(
  ui = ui,
  server = server)

推荐阅读