開始使用免費開始

用 observeEvent() 觸發反應

有些時候你會想在某個事件發生時執行一個動作。 例如,當使用者點擊「Download」按鈕時,讓他們把表格下載成 CSV 檔。或者,你可能想在按下某個按鈕後,顯示一個通知或彈出視窗(modal dialog)。

observeEvent() 函式可以達成這些需求。它接受兩個引數:

  1. 你要監聽並回應的事件。
  2. 每次該事件發生時要呼叫的函式。

在這個練習中,當使用者點擊標示為「Help」的按鈕時,你會用 observeEvent() 顯示一個包含說明文字的彈出視窗。說明文字已指派給變數 bmi_help_text

本練習屬於課程

使用 R 的 Shiny 建立網頁應用程式

檢視課程

練習說明

  • UI:
    • 新增一個名為 'show_help'、標籤為「Help」的動作按鈕。你可能需要往下捲動或收合主控台才能看到 UI。
  • Server:
    • 取消註解 # showModal ... 這段程式碼。
    • observeEvent() 包住 showModal(...),讓使用者點擊 Help 按鈕時顯示說明文字。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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)
編輯並執行程式碼