我想要一个按钮来触发对预定的非反应变量x
的操作。每次按下按钮,均应执行x <- x + 1
。为了检查是否正确完成,应显示结果。
为此,我尝试了observeEvent()
。但是它只做一次。如何正常运作?
似乎rv
仅在observeEvent()
函数中可用。如果output$text_2 <- renderText({ rv$a })
放在observeEvent()
之外,则会发生错误。如何在observeEvent()
之外使用它完成的工作?
library(shiny)
x <- 0
ui <- fluidPage(
actionButton(inputId = "action",
label = "action"),
textOutput("text_1"),
textOutput("text_2")
)
server <- function(input, output) {
output$text_1<- renderText({ input$action })
observeEvent(input$action, {
x <- x + 1
rv <- reactiveValues(a = x)
output$text_2 <- renderText({ rv$a })
})
}
shinyApp(ui = ui, server = server)
最佳答案
Daattalis的答案很明显,但我想我可以发布一些示例,说明如何使用Shinys反应式值来做到这一点。
library(shiny)
ui <- fluidPage(
actionButton(inputId = "action",
label = "action"),
textOutput("txt_example1"),
textOutput("txt_example2"),
textOutput("txt_example3")
)
server <- function(input, output) {
# ------------------ Example 1 ------------------
# Use a list of reactive values
rv <- reactiveValues(x=0)
# Will update text output when rv$x is updated
observe({
output$txt_example1 <- renderText({ rv$x })
})
# ------------------ Example 2 ------------------
# Make variable a reactive
x <- 0
makeReactiveBinding('x')
# The only 'trick' here is that x is made a reactive so that the observer is
# triggered every time x is updated.
# If x is not made a reactive the value of x will still be updated but the observer
# wont trigger (see example 3).
observe({
output$txt_example2 <- renderText({ x })
})
# ------------------ Example 3 ------------------
# Use ordinary R scoping
x2 <- 0
printUpdate <- function(){
output$txt_example3 <- renderText({ x2 })
}
printUpdate() # Print first value
# onClick listener, same for all examples
observeEvent(input$action, {
rv$x <- rv$x + 1 # Example 1, update reactive list
x <<- x + 1 # Example 2, Save x to parent enviroment
# Example 3
x2 <<- x2 + 1 # Again, save x2 to parent enviroment, see help('<<-')
printUpdate() # Update textOutput
})
}
shinyApp(ui = ui, server = server)
希望这可以帮助!