observeEvent()로 반응 트리거하기
이벤트에 반응하여 어떤 동작을 수행해야 할 때가 있습니다. 예를 들어, 사용자가 "Download" 버튼을 클릭했을 때 표를 CSV 파일로 다운로드하도록 하거나, 클릭에 반응해 알림 또는 모달 대화 상자를 표시하고 싶을 수 있어요.
observeEvent()를 사용하면 이런 동작을 구현할 수 있습니다. 이 함수는 두 개의 인수를 받습니다:
- 반응할 이벤트
- 이벤트가 발생할 때마다 호출할 함수
이번 연습에서는 사용자가 "Help"라는 레이블의 버튼을 클릭하면 도움말 텍스트가 담긴 모달 대화 상자를 표시하도록 observeEvent()를 사용합니다. 도움말 텍스트는 이미 bmi_help_text 변수에 할당되어 있습니다.
이 연습은 강의의 일부입니다
R로 Shiny 웹 애플리케이션 만들기
연습 안내
- UI:
- 'show_help'라는 이름의 액션 버튼을 추가하고 레이블은 "Help"로 지정하세요. UI를 보려면 아래로 스크롤하거나 콘솔을 접어야 할 수도 있어요.
- Server:
# showModal ...코드를 주석 해제하세요.- 사용자가 Help 버튼을 클릭했을 때 도움말 텍스트가 표시되도록
showModal(...)을(를)observeEvent()로 감싸세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
ui <- fluidPage(
titlePanel('BMI Calculator'),
sidebarLayout(
sidebarPanel(
textInput('name', 'Enter your name'),
numericInput('height', 'Enter your height in meters', 1.5, 1, 2),
numericInput('weight', 'Enter your weight in Kilograms', 60, 45, 120),
actionButton("show_bmi", "Show BMI")
# CODE BELOW: Add an action button named "show_help"
),
mainPanel(
textOutput("bmi")
)
)
)
server <- function(input, output, session) {
# MODIFY CODE BELOW: Wrap in observeEvent() so the help text
# is displayed when a user clicks on the Help button.
# Display a modal dialog with bmi_help_text
# MODIFY CODE BELOW: Uncomment code
# showModal(modalDialog(bmi_help_text))
rv_bmi <- eventReactive(input$show_bmi, {
input$weight/(input$height^2)
})
output$bmi <- renderText({
bmi <- rv_bmi()
paste("Hi", input$name, ". Your BMI is", round(bmi, 1))
})
}
shinyApp(ui = ui, server = server)