首页 > 解决方案 > 访问 eventReactive 中的值

问题描述

我需要一个基本的 Shiny 问题的帮助。我的目标是制作一个简单的数学测验应用程序(什么是 4 x 4?)。我想用一个按钮创建值,选择一个数字答案,然后按另一个答案按钮。我的问题是我找不到访问存储在 eventReactive 中的值的方法。我在下面的代码中简化了问题。这个应用程序的目标是要求一个号码,然后提供它。先感谢您!

# Goal: Fetch a number, then input that number, then receive paste("correct")/paste("incorrect)

ui <- fluidPage(
      textOutput(outputId = "out"),

      numericInput(inputId = "inn",
               label = "",
               value = 0),

  actionButton("answer", "Answer"),
  actionButton("question", "New Question"),
)




server <- function(input, output) {

  data <- eventReactive(input$question,{

    a <- sample.int(10,1)

    paste("Enter",a)

    })

  output$out <- renderText({data()})

}

shinyApp(ui,server)

标签: shinyshiny-reactivity

解决方案


这是我会做的

ui <- fluidPage(

      textOutput(outputId = "out"),
      numericInput(inputId = "inn", label = "", value = 0),
      actionButton("answer", "Answer"),
      actionButton("question", "New Question"),

)

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

    data <- reactiveValues(number = NULL)

    output$out <- renderText({
        if (is.null(data$number))
            "Press 'New Question' button"
        else
            paste("Enter", data$number)
    })

    observeEvent(input$question, {
        data$number = sample(10, 1)
     })

    observeEvent(input$answer, {
        req(data$number, input$inn)
        if (data$number == input$inn)
            print("Correct")
            # Do something exciting
        else
            print("Incorrect")
            # Do something else
    })

}

shinyApp(ui,server)

IMO 将反应数据和输入/输出生成分开是一种很好的做法。我的意思是在上面的例子中我们使用

  • reactiveValues跟踪不断变化的数据,以及
  • observeEvent监控可能会改变我们反应数据的特定元素的按钮点击,
  • renderText可以打印固定文本或反应数据。

推荐阅读