首页 > 解决方案 > 在闪亮的第一个默认值后隔离输入

问题描述

我正在使用动态 UI,并希望选择默认值和输入,隔离以下值。

在以下示例中,我可以隔离默认值 ( value = isolate(input$dynamic)),但我无法设置默认值(不同于最小值)。

有没有办法同时做(设置值和隔离之后)?

library(shiny)

ui <- fluidPage(
        fluidRow(
            textInput("label", "labelasd"),
            selectInput("type_of_pe", "Type of policy estimate", c("type 1", "type 2", "type 3")), 
            uiOutput("data_in")
        )
    )

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

    output$data_in <- renderUI({
        output <- tagList()
        output [[1]] <- sliderInput("dynamic", input$label, value = isolate(input$dynamic), min = 0, max = 100)
        output [[2]] <- sliderInput("dynamic", input$label, value = isolate(input$dynamic) * 20, min = 5, max = 20)
        if (input$type_of_pe == "type 1") {
            lapply( 1, function(x) output[[x]] )
        } else if (input$type_of_pe == "type 2") {
            lapply( 2, function(x) output[[x]] )
        } else if (input$type_of_pe == "type 3") {
            lapply( c(1,2), function(x) output[[x]] )
        }

    })
     }
shinyApp(ui = ui, server = server)

标签: rshiny

解决方案


您可以使用响应值来指定是使用默认值还是使用来自 的值input$dynamic

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

  # initialize reactive value as TRUE
  use_default <- reactiveVal(T)
  # if slider is moved, stop using the default
  observeEvent(input$dynamic, ignoreInit=T, {
    use_default(F)
  })

  output$data_in <- renderUI({
    # check whether the value should use default or not (default is set to 10)
    value <- if (use_default()) 10 else isolate(input$dynamic)
    output <- tagList()
    output [[1]] <- sliderInput("dynamic", input$label, value = value, min = 0, max = 100)
    output [[2]] <- sliderInput("dynamic", input$label, value = value * 20, min = 5, max = 20)
    if (input$type_of_pe == "type 1") {
      lapply( 1, function(x) output[[x]] )
    } else if (input$type_of_pe == "type 2") {
      lapply( 2, function(x) output[[x]] )
    } else if (input$type_of_pe == "type 3") {
      lapply( c(1,2), function(x) output[[x]] )
    }

  })
}

推荐阅读