当使用几个操作按钮时,理解为什么闪亮中的操作按钮不起作用按钮、几个、操作、不起作用

2023-09-03 14:09:49 作者:一句忘记,谈何容易。

为什么当我将SHINY手册(https://shiny.rstudio.com/articles/action-buttons.html)中的几个操作按钮代码组合在一起时,它不运行(即没有按钮反应)?每个代码单独运行都很好。怎么才能修好呢? (这与此帖子相关:Convert Shiny App R code to Rmarkdown Shiny App code: with observeEvent and eventReactive)

# Code from https://shiny.rstudio.com/articles/action-buttons.html

library(shiny)

ui <- fluidPage(
  # Pattern 1 - Command
  tags$head(tags$script(src = "message-handler.js")),
  actionButton("do", "Click Me"),
  hr(),

  # Pattern 2 - Delay reactions
  actionButton("go", "Go"),
  numericInput("n", "n", 50),
  plotOutput("plot2"), 
  hr(),

  # Pattern 4 - Reset buttons
  actionButton("runif", "Uniform"),
  actionButton("reset", "Clear"),
  plotOutput("plot4")
  
)

server <- function(input, output, session) {
  
  # Pattern 1 - Command
  observeEvent(input$do, {
    session$sendCustomMessage(type = 'testmessage',
                              message = 'Thank you for clicking')
  })

  # Pattern 2 - Delay reactions
  randomVals <- eventReactive(input$go, {
    runif(input$n)
  })
  output$plot2 <- renderPlot({
    hist(randomVals())
  })
  
  # Pattern 4 - Reset buttons
  v <- reactiveValues(data = NULL)
  observeEvent(input$runif, {
    v$data <- runif(100)
  })
  observeEvent(input$reset, {
    v$data <- NULL
  })
  output$plot4 <- renderPlot({
    if (is.null(v$data)) return()
    hist(v$data)
  })
}

shinyApp(ui, server)

更新:

一篇文章带你全面了解按钮

在原始问题中,我有模式2和模式4中的output$plot示例。现在它们已被替换为output$plot2output$plot4-这部分解决了问题。-模式2和模式4的按钮现在可以使用。但是,模式%1仍然不起作用。

推荐答案

按照建议,您不能有两个ID相同的输出。请尝试此操作

library(shiny)

ui <- fluidPage(
  # Pattern 1 - Command
  #tags$head(tags$script(src = "message-handler.js")),
  actionButton("do", "Click Me"),
  hr(),
  
  # Pattern 2 - Delay reactions
  actionButton("go", "Go"),
  numericInput("n", "n", 50),
  #plotOutput("plot"), 
  #hr(),
  
  # Pattern 4 - Reset buttons
  actionButton("runif", "Uniform"),
  actionButton("reset", "Clear"),
  plotOutput("plot")
  
)

server <- function(input, output, session) {
  
  # Pattern 1 - Command
  observeEvent(input$do, {
    # session$sendCustomMessage(type = 'testmessage',
    #                           message = 'Thank you for clicking')
    print('Thank you for clicking')
  })
  
  ### Pattern 2 - Delay reactions
  randomVals <- eventReactive(input$go, {
    runif(input$n)
  })
  
  ### Pattern 4 - Reset buttons
  v <- reactiveValues(data = NULL)
  observeEvent(input$runif, {
    v$data <- runif(100)
  })
  observeEvent(input$go, {
    v$data <- runif(input$n)
  })
  observeEvent(input$reset, {
    v$data <- NULL
  })
  output$plot <- renderPlot({
    if (is.null(v$data)) {
      return()
    }else {
      hist(v$data)
    }

  })
}

shinyApp(ui, server)