如何构建一个仅在用户单击单击按钮时才显示输出的闪亮应用程序?

How to build a shiny app that shows the output ONLY when the user clicks a click button?

我想构建一个简单的 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。但是,第一次点击后,应用程序不关心你是否点击,它会自动显示带有滑块的所选数字。

我错过了什么?

您可以使用 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)

我发现另一种有用的方法是将值存储在 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)