使用 eventReactive() 延後反應
Shiny 的反應式程式設計架構會在輸入有變更時,自動更新所有相依的輸出。不過在某些情況下,你可能會想要明確控制觸發更新的事件。
eventReactive() 會計算一個反應式值,且只會在特定事件發生時才更新。
rval_x <- eventReactive(input$event, {
# 計算
})
本練習屬於課程
使用 R 的 Shiny 建立網頁應用程式
練習說明
- 使用
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)