不需要时,在R Shiny中禁用selectInput

msa*_*eri 0 r shiny

我正在构建一个shiny包含两个表单的网页selectInput:第一个 - 静态 - 在ui部分中,第二个 - 动态 - 在server部分中.下面显示了真实问题的简化.

require(shiny)

ui <- fluidPage(

    # The static input
    selectInput(inputId = 'static',
                label = 'Make a choice',
                choices = c('A', 'B', 'C'),
                selectize = FALSE),

    # The dynamic input
    uiOutput(outputId = 'dynamicInput'),

    # The output
    hr(),
    strong('This is a check for the output:'),
    textOutput(outputId = 'check')

)

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

    # The dynamic input definition
    output$dynamicInput <- renderUI({

        # This input exists if the `static`
        # one is equal to `A` only
        if (input$static == 'A') {
            selectInput(inputId = 'dynamic',
                        label = 'Choose a subset for `A`',
                        choices = c('A1', 'A2', 'A3'),
                        selectize = FALSE)
        } else {
            return(NULL)
        }

   })

   # The example output
   output$check <- renderText({

       paste(input$static, input$dynamic)

   })

}

shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)

在实际情况下,我必须基于静态输入在数据库上启动查询,最终是动态查询(如果存在).

在测试应用程序时,我selectInput在第一轮中正确获得了动态,我可以选择 - 让我们说 - A2选项.然后,如果我选择B静态selectInput,动态输入不响应,仍然显示先前的选择而不是显示NULL.

selectInput如果静态不等于动态,如何强制动态复位A?我是否必须使用Dean Attali的一些技巧手动隐藏它?shinyjs

dva*_*las 5

试试这个吧.它是使用反应值和观察的组合.

require(shiny)

ui <- fluidPage(

  # The static input
  selectInput(inputId = 'static',
              label = 'Make a choice',
              choices = c('A', 'B', 'C'),
              selectize = FALSE),

  # The dynamic input
  uiOutput(outputId = 'dynamicInput'),

  # The output
  hr(),
  strong('This is a check for the output:'),
  textOutput(outputId = 'check')

)

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

  ## list to store reactive values
  values <- reactiveValues()


  # The dynamic input definition
  output$dynamicInput <- renderUI({

    # This input exists if the `static`
    # one is equal to `A` only
    if (input$static == 'A') {
      selectInput(inputId = 'dynamic',
                  label = 'Choose a subset for `A`',
                  choices = c('A1', 'A2', 'A3'),
                  selectize = FALSE)
    } else {
      return(NULL)
    }

  })

  ## this bit fixes the issue
  observe({
    if (input$static == "A") {
      values$dyn <- input$dynamic
    } else {
      values$dyn <- NULL
    }
  })

  # The example output
  output$check <- renderText({

    paste(input$static, values$dyn)

  })

}

shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)