You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny应用问题:未触发Submit按钮却显示CSS加载器

解决Shiny应用初始显示加载器的问题

要实现点击"Submit"按钮前不显示加载器,你可以通过条件渲染输出区域的方式解决,只有当按钮被点击后才渲染带加载器的图表容器。以下是修改后的完整代码:

# Load required libraries
library(shiny)
library(shinydashboard)
library(plotly)

# Define UI
ui <- dashboardPage(
  dashboardHeader(title = "SelectInput with Action Button Dashboard"),
  dashboardSidebar(),
  dashboardBody(
    # Box with selectInput and actionButton
    box(
      title = "SelectInput and ActionButton Box",
      width = 6,
      height = 400,
      solidHeader = TRUE,
      collapsible = TRUE,
      status = "primary",
      selectInput("choice", "Select a choice:", choices = c("Option 1", "Option 2")),
      actionButton("submitButton", "Submit"),
      # 仅在按钮点击后显示带加载器的图表区域
      conditionalPanel(
        condition = "input.submitButton > 0",
        shinycssloaders::withSpinner(
          plotlyOutput("outputPlot"),
          type = 5,
          color = "#0dc5c1",
          size = 2
        )
      )
    )
  )
)

# Define server
server <- function(input, output) {
  observeEvent(input$submitButton, {
    # Plot based on the selected choice
    if (input$choice == "Option 1") {
      output$outputPlot <- renderPlotly({
        # 模拟加载延迟,方便看到加载器效果
        Sys.sleep(1)
        plot_ly(x = c(1, 2, 3), y = c(10, 11, 12), type = 'scatter', mode = 'lines+markers')
      })
    } else if (input$choice == "Option 2") {
      output$outputPlot <- renderPlotly({
        Sys.sleep(1)
        plot_ly(x = c(1, 2, 3), y = c(5, 8, 10), type = 'bar')
      })
    }
  })
}

# Create Shiny app
shinyApp(ui, server)

关键改动说明:

  • 用conditionalPanel包裹带加载器的plotlyOutput,设置触发条件为input.submitButton > 0——只有当按钮被点击过(点击次数大于0)时,才会渲染这个区域。
  • 初始状态下按钮点击次数为0,图表区域和加载器都不会显示;点击按钮后条件触发,加载器会在图表渲染过程中显示,渲染完成后自动消失。
  • 代码中添加了Sys.sleep(1)模拟加载延迟,方便直观看到加载器效果,实际使用时可按需删除。

内容的提问来源于stack exchange,提问作者firmo23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 05:33:41