【问题标题】:How to build a shiny app that shows the output ONLY when the user clicks a click button?如何构建仅在用户单击单击按钮时才显示输出的闪亮应用程序?
【发布时间】:2021-12-28 07:05:54
【问题描述】:

我想构建一个简单的shiny 应用程序,它接受一个数字input$number在用户点击 (input$click) 时打印此数字。

到目前为止,我已经尝试过:

library(shiny)

ui = fluidPage(
        sliderInput("number", "number", value = 10, min = 0, max = 50),
        actionButton("click", "Change output"),
        textOutput("text")
)

server = function(input, output, session) {
        
        observeEvent(input$click, {
                output$text = renderText({
                        print(input$number)
                })
        })
}

shinyApp(ui, server)

当应用程序首次启动时,它会等待用户单击,然后才会显示输出 text。但是,第一次点击后,应用程序不管你是否点击,它会自动显示选择的数字并带有滑块。

我错过了什么?

【问题讨论】:

    标签: r shiny shiny-reactivity


    【解决方案1】:

    您可以使用isolate 来防止反应

    library(shiny)
    
    ui = fluidPage(
      sliderInput("number", "number", value = 10, min = 0, max = 50),
      actionButton("click", "Change output"),
      textOutput("text")
    )
    
    server = function(input, output, session) {
    
      output$text = renderText({
          input$click
          req(input$click) #to prevent print at first lauch
          isolate(print(input$number))
      })
    }
    
    shinyApp(ui, server)
    

    【讨论】:

    【解决方案2】:

    我认为有用的另一种方法是将值存储在 reactiveValues 列表中,然后使用事件观察器更新它们。

    library(shiny)
    
    SLIDER_INIT <- 10
    
    ui = fluidPage(
      sliderInput("number", "number", value = SLIDER_INIT, min = 0, max = 50),
      actionButton("click", "Change output"),
      textOutput("text")
    )
    
    server = function(input, output, session) {
      
      # Store values that will need to be displayed to the user here.
      AppValues <- reactiveValues(
        slider_number = 10
      )
      
      # Change reactive values only when an event occurs.
      observeEvent(
        input$click, 
        {
          AppValues$slider_number <- input$number
        }
      )
      
      # Display the current value for the user.
      output$text = renderText({
        AppValues$slider_number
      })
    }
    
    shinyApp(ui, server)
    

    【讨论】:

      猜你喜欢
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多