使用 eventReactive() 延迟响应
Shiny 的响应式编程框架旨在让任何输入的变化都会自动更新依赖它的输出。在某些情况下, 我们希望显式控制触发更新的事件。
函数 eventReactive() 用于计算一个仅在特定事件发生时才会更新的响应式值。
rval_x <- eventReactive(input$event, {
# 计算
})
本练习是课程的一部分
使用 R 构建 Shiny Web 应用
练习说明
- 使用
eventReactive(),在用户点击按钮之前延迟 BMI 的计算执行。
交互式实操练习
通过完成这段示例代码来试试这个练习。
ui <- fluidPage(
titlePanel('BMI Calculator'),
sidebarLayout(
sidebarPanel(
textInput('name', 'Enter your name'),
numericInput('height', 'Enter height (in m)', 1.5, 1, 2, step = 0.1),
numericInput('weight', 'Enter weight (in Kg)', 60, 45, 120),
actionButton("show_bmi", "Show BMI")
),
mainPanel(
textOutput("bmi")
)
)
)
server <- function(input, output, session) {
# MODIFY CODE BELOW: Use eventReactive to delay the execution of the
# calculation until the user clicks on the show_bmi button (Show BMI)
rval_bmi <- reactive({
input$weight/(input$height^2)
})
output$bmi <- renderText({
bmi <- rval_bmi()
paste("Hi", input$name, ". Your BMI is", round(bmi, 1))
})
}
shinyApp(ui = ui, server = server)