R Shiny:在单击操作按钮之前阻止 cssloader 显示

R Shiny: Prevent cssloader from showing until action button is clicked

我想在某些处理完成时显示一个 cssloader 微调器。 cssloader 必须在点击 actionButton 后才会显示,这会触发数据处理(这一步需要一些时间,由下面示例中的 sys.Sleep() 函数模拟)。此外,我希望它在每次由 actionButton 触发此操作时显示,而不仅仅是第一次。

这是我正在尝试的示例:

library(shiny)
library(shinycssloaders)

ui <- fluidPage(
   titlePanel("CSS loader test"),

   sidebarLayout(
      sidebarPanel(
         selectInput("imageOptions", "Choose an image:", choices = list(option1="RStudio-Logo-Blue-Gradient.png", option2="RStudio-Logo-All-Gray.png")),
         actionButton("getImage", "Show image:")
      ),

      mainPanel(
         withSpinner(uiOutput("logo"))
      )
   )
)

server <- function(input, output) {
  url<-reactive(
   paste0("https://www.rstudio.com/wp-content/uploads/2014/07/", input$imageOptions)
   )

  observeEvent(input$getImage,{
    output$logo<-renderText({
      URL<-isolate(url())
      print(URL)
      Sys.sleep(2)
      c('<center><img src="', URL, '"width="50%" height="50%" align="middle"></center>')
    })
  })

}
# Run the application 
shinyApp(ui = ui, server = server)

我敢打赌有更好的方法来完成我需要的,但这里有一个解决方案:

library(shiny)
library(shinycssloaders)

ui <- fluidPage(
  titlePanel("CSS loader test"),

  sidebarLayout(
    sidebarPanel(
      selectInput("imageOptions", "Choose an image:", choices = list(option1="RStudio-Logo-Blue-Gradient.png", option2="RStudio-Logo-All-Gray.png")),
      actionButton("getImage", "Show image:")
    ),

    mainPanel(
      withSpinner(uiOutput("logo"))
    )
  )
)

server <- function(input, output) {
  url<-reactive(
    paste0("https://www.rstudio.com/wp-content/uploads/2014/07/", input$imageOptions)
  )
  output$logo<-renderText({
    validate(need(input$getImage, "")) #I'm sending an empty string as message.
    input$getImage
      URL<-isolate(url())
      print(URL)
      Sys.sleep(2)
      c('<center><img src="', URL, '"width="50%" height="50%" align="middle"></center>')
  })
}
# Run the application 
shinyApp(ui = ui, server = server)

不是通过调用 observeEvent 获得反应性,有效的解决方案是在 render 函数内调用 validate(need(input$getImage, ""))