如何让Shiny中的reset按钮自动触发apply按钮点击?
解决Shiny应用中Reset按钮自动触发Apply的问题
你的代码逻辑思路是对的,但因为缺少shinyjs包的初始化配置,导致自动点击Apply的功能没生效。下面是修复后的完整代码:
# Libraries ---- library(tidyverse) library(shiny) library(shinydashboard) library(shinyjs) # 新增:加载shinyjs包 data <- mtcars %>% as_tibble() # UI ---- ui <- dashboardPage( dashboardHeader(), dashboardSidebar( pickerInput( inputId = "cyl_picker", label = "Cylinder", choices = unique(data$cyl), selected = unique(data$cyl), multiple = TRUE ), # * Apply Button ---- actionButton( inputId = "apply", label = "Apply", icon = icon(name = "play", lib = "font-awesome") ), # * Reset Button ---- actionButton( inputId = "reset", label = "Reset", icon = icon("sync") ) ), dashboardBody( shinyjs::useShinyjs(), # 新增:启用shinyjs功能 dataTableOutput("test_table") ) ) # Server ---- server <- function(input, output) { # Data Setup ---- data_filtered <- eventReactive(eventExpr = input$apply, valueExpr = { data %>% filter(cyl %in% input$cyl_picker) }, ignoreNULL = FALSE ) # Datatable ---- output$test_table <- renderDataTable(({data_filtered()})) # Apply / Reset Reactive ---- shiny::observeEvent(eventExpr = input$reset, handlerExpr = { # * Reset Date Range Input ---- updatePickerInput( session = getDefaultReactiveDomain(), inputId = "cyl_picker", choices = unique(data$cyl), selected = unique(data$cyl) ) # * Reset Button Reactive ---- shinyjs::delay(ms = 300, expr = { shinyjs::click(id = "apply") }) }) } shinyApp(ui, server)
关键修改说明
- 加载
shinyjs包:你用到的delay()和click()函数都属于shinyjs,必须先加载这个包才能使用 - 启用shinyjs功能:在UI的
dashboardBody中添加shinyjs::useShinyjs(),这是让shinyjs生效的必要步骤,它会注入对应的JavaScript代码到页面中
如果还没安装shinyjs,先运行以下命令安装:
install.packages("shinyjs")
现在点击Reset按钮后,会先重置选择器,延迟300毫秒后自动触发Apply按钮,数据表会自动更新为默认过滤状态。
内容的提问来源于stack exchange,提问作者The Rookie
相关产品推荐
相关产品推荐

