繁体   English   中英

在Shiny中使用observeEvent时,如何多次渲染?

[英]How to render more than once when using observeEvent in shiny?

我使用shiny的R和想用的时候渲染不止一次observeEvent在server.R

我不明白为什么这行不通:

library(shiny)

my_UI <- fluidPage(
  fluidRow(actionButton("test", "test")),
  fluidRow(textOutput("out"))
)

my_Server <- function(input, output) {
  observeEvent(input$test, {
    output$out <- renderText("waiting")
    Sys.sleep(2)
    output$out <- renderText("done")
  })
}

shinyApp(my_UI, my_Server)

我也尝试过:

library(shiny)

my_UI <- fluidPage(
  fluidRow(actionButton("test", "test")),
  fluidRow(textOutput("out"))
)

my_Server <- function(input, output) {

  observeEvent(input$test, {
    output$out <- renderText("waiting")
  })
  observeEvent(input$test, {
    Sys.sleep(2)
    output$out <- renderText("done")
  })
}

shinyApp(my_UI, my_Server)

在这两种情况下,仅呈现后一个消息……我在这里做错了什么? 谢谢!

我无法在一个observeEvent中为每一行渲染提供解决方案,但是如果您只想显示加载/计算进度,则可以使用

withProgress()

所以应用程序可以像这样:

library(shiny)

my_UI <- fluidPage(
  fluidRow(actionButton("test", "test")),
  fluidRow(textOutput("out"))
)

my_Server <- function(input, output) {

  observeEvent(input$test, {
    withProgress(
      message = 'Calculation in progress',
      detail = 'This may take a while...', value = 0, {
        incProgress(1/2, message = "Step 1")
        Sys.sleep(2)
        # Do some stuff, load, calculate, etc
        incProgress(1/2, message = "Step 2")
      })
  })
}

shinyApp(my_UI, my_Server)

您无法使用Shiny进行此操作,因为将仅使用最新的输出值。

你可以用JavaScript做,但你可能有更好的选择,即withProgress为feniw_fx mentionned

library(shiny)
my_UI <- fluidPage(
  tags$head(
    tags$script(
      "function test() {
      document.getElementById('out').innerHTML = 'waiting';
      setTimeout(function() {document.getElementById('out').innerHTML = 'done'}, 2000);}"
  )),
  fluidRow(actionButton("test", "test", onclick = "test()")),
  fluidRow(textOutput("out"))
)

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

}

shinyApp(my_UI, my_Server)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM