开始使用免费开始使用

Trigger reactions with observeEvent()

There are times when you want to perform an action in response to an event. For example, you might want to let the app user download a table as a CSV file, when they click on a "Download" button. Or, you might want to display a notification or modal dialog, in response to a click.

The observeEvent() function allows you to achieve this. It accepts two arguments:

  1. The event you want to respond to.
  2. The function that should be called whenever the event occurs.

In this exercise, you will use observeEvent() to display a modal dialog with help text, when the user clicks on a button labelled "Help". The help text has already been assigned to the variable bmi_help_text.

本练习是课程的一部分

Building Web Applications with Shiny in R

查看课程

练习说明

  • UI:
    • Add an action button named 'show_help', labelled "Help". You might have to scroll down or collapse the console to view the UI.
  • Server:
    • Uncomment the code # showModal ...
    • Wrap showModal(...) in observeEvent() so that the help text is displayed when a user clicks on the help button

交互式实操练习

通过完成这段示例代码来试试这个练习。

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)
编辑并运行代码