首页 文章

在Shiny中禁用按钮

提问于
浏览
2

我正在编写一些Shiny代码,用户将在该应用程序中输入一些输入,然后单击一个操作按钮 . 操作按钮会触发一系列模拟运行需要很长时间,所以我想在单击操作按钮后将其禁用,以便用户在模拟运行之前无法一直点击它 . 我遇到了 shinyjs::enableshinyjs::disable 函数,但一直很难利用它们 . 这是我的服务器代码:

output$button1= renderUI({
        if(input$Button1 > 0)  {
          shinyjs::disable("Button1")
                tableOutput("table")
          shinyjs::enable("Button1")}
  })

但是,当我使用此代码时,单击操作按钮没有任何反应 . 即,操作按钮不会变灰,也不会生成表格 . 但是,当我拿走 shinyjs::enable() 命令时,即,

output$button1= renderUI({
            if(input$Button1 > 0)  {
              shinyjs::disable("Button1")
                    tableOutput("table")
}
      })

首先生成表格,然后按钮变为灰色,但我希望按钮变为灰色,然后表格生成自己 .

我在这做错了什么?


Here is my updated code based on Geovany's suggestion yet it still doesn't work for me

Button1Ready <- reactiveValues(ok = FALSE)

        observeEvent(input$Button1,  {
          shinyjs::disable("Button1")
          RunButton1Ready$ok <- FALSE
          RunButton1Ready$ok <- TRUE
  })

output$SumUI1= renderUI({
        if(Button1Ready$ok){
          tableOutput("table")
          shinyjs::enable("Button1")
        }
})

在哪里澄清我还:

output$table <- renderTable({

#My code....

)}

1 回答

  • 9

    我认为你在相同的反应函数中使用 shinyjs::disableshinyjs::enable . 你只会看到最后的效果 . 我建议你将 disable/enable 分成不同的反应函数,并使用一些额外的反应变量来控制按钮的重新激活 .

    我不知道你的代码究竟是多么准确,但是在下面的代码中说明了这个想法 .

    library(shiny)
    library(shinyjs)
    
    
    ui <- fluidPage(
      shinyjs::useShinyjs(),
      sidebarLayout(
        sidebarPanel(
          actionButton("Button1", "Run"),
          shinyjs::hidden(p(id = "text1", "Processing..."))
        ),
        mainPanel(
           plotOutput("plot")
        )
      )
    )
    
    server <- function(input, output) {
    
      plotReady <- reactiveValues(ok = FALSE)
    
      observeEvent(input$Button1, {
        shinyjs::disable("Button1")
        shinyjs::show("text1")
        plotReady$ok <- FALSE
        # do some cool and complex stuff
        Sys.sleep(2)
        plotReady$ok <- TRUE
      })  
    
      output$plot <-renderPlot({
        if (plotReady$ok) {
          shinyjs::enable("Button1")
          shinyjs::hide("text1")
          hist(rnorm(100, 4, 1),breaks = 50)
        }
      })
    }
    
    shinyApp(ui, server)
    

相关问题