繁体   English   中英

使用observeEvent 更新闪亮的输入

[英]update shiny input with observeEvent

我希望用户定义一个初始数值,然后通过每次单击操作按钮按设定的数量更新(即添加)该数值。 我使用reactiveVal 来尝试进行此更新,但是在没有主动响应上下文错误的情况下,无法执行可怕的操作 我很困惑,因为我认为使用 reactVal是在响应式表达式中做一些事情,但显然我错了。

我已经寻找了相关的问题/文章/教程,但结果是空的。 非常感谢任何建议。 请让我知道是否有更好的方法来完成这项任务,即我是否应该使用不同的函数或方法。

我的代码的精简版本如下:

library(shiny)

ui <- fluidPage(

    ## initilize the value
    numericInput('init.i','initial i',10),

    ## click this button to add one to the initial value
    actionButton("run","Run"),

    ## output the current count
    textOutput("cur.i")

)

server <- function(input,output) {

    ## define the current value according to the inital value
    i <- reactiveVal({
        input$init.i ## this line fails
        ##1 ## this line doesn't fail but value always initializes at 1 
    })

    observeEvent(input$run, {
        ## make a new value by adding 1 to the current value
        new.i <- i() + 1
        ## update the value
        i(new.i)

        output$cur.i <- renderText({
            ## print the current value
            i()
        })
    })

}

shinyApp(ui=ui,server=server)

以下作品。 正如闪亮向您报告的那样,您尝试做的事情是不允许的。 这是i()的初始化,您使用input$init.i需要反应性上下文。

想要的效果可以通过在您想要的初始值( input$init.i )上创建另一个observeEvent来实现,将您的反应值设置为该值。

library(shiny)
ui <- fluidPage(

  ## initilize the value
  numericInput('init.i','initial i', 10),

  ## click this button to add one to the initial value
  actionButton("run","Run"),

  ## output the current count
  textOutput("cur.i")

)
server <- function(input,output) {

  ## Define the reactive value (with no 'inital' value)
  i <- reactiveVal()

  ## Set i() based on "initialize" input widget
  observeEvent(input$init.i, { 
    i(input$init.i)
  })

  observeEvent(input$run, {
    ## make a new value by adding 1 to the current value
    new.i <- i() + 1
    ## update the value
    i(new.i)
   })

  output$cur.i <- renderText({
    i()
  })
}
shinyApp(ui = ui, server = server)

此外,无需将renderText嵌套在observeEvent

暂无
暂无

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

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