【问题标题】:Update label of actionButton in shiny更新闪亮的actionButton标签
【发布时间】:2016-02-20 01:36:02
【问题描述】:

我知道类似的question 已经得到回答,但是该解决方案会在字符串输入时创建一个具有不同标签的新actionButton。我需要的是保留按钮(按钮的计数器),因为当我更改标签并创建一个新按钮时,它的计数器为 0(未单击)。

所以基本上我需要一个更新函数之类的东西来改变actionButton的标签,当它被按下时。你按下它一次,标签就会改变。

input$Button <- renderUI({
    if(input$Button >= 1) label <- "new label"
    else label <- "old label"
    actionButton("Button", label = label)
})

类似这样,但没有重置按钮的值(通过创建一个全新的按钮)。

谢谢!

【问题讨论】:

    标签: r shiny


    【解决方案1】:
    1. reactiveValues() 可以提供帮助。详情请查看http://shiny.rstudio.com/articles/reactivity-overview.html。 在以下示例中,我将您的 input$Button 重命名为 input$click 以避免重复使用“按钮”名称。 由于我们将标签包装在renderUI() 中,input$click 在创建后最初会触发?!?,这就是我放置标签的原因 条件为:if(vars$counter &gt;= 2)

    2. 另一种解决方案是删除只读属性(可在此处找到:https://github.com/rstudio/shiny/issues/167

      attr(input, "readonly") <- FALSE
      input$click <- 1
      
    3. 举个例子 将以下内容粘贴到您的 R 控制台中:

      ui <- bootstrapPage(
          uiOutput('Button')
      )
      
      server <- function(input, output) {
      
          # store the counter outside your input/button
          vars = reactiveValues(counter = 0)
      
          output$Button <- renderUI({
              actionButton("click", label = label())
          })
      
          # increase the counter
          observe({
              if(!is.null(input$click)){
                  input$click
                  isolate({
                      vars$counter <- vars$counter + 1
                  })
              }
          })
      
          label <- reactive({
              if(!is.null(input$click)){
                  if(vars$counter >= 2) label <- "new label"
                  else label <- "old label"
              }
          })
      }
      
      # run the app
      shinyApp(ui = ui, server = server)
      

    【讨论】:

    • 我的问题是,我使用 input$click(in your template) 来激活另一个功能,当生成一个新按钮时,它会自动取消点击,所以我的功能消失了。使用此解决方案,问题仍然存在,但由于您的解决方案很优雅,让我意识到我在控制流中的错误并修复它,谢谢。我希望其他人也觉得这很有用。
    • 我认为使用session$sendCustomMessage 更新按钮会是一种更好的方法,因为它可以消除重新创建按钮的需要
    • 我似乎找不到有关此功能的任何文档。您能否简要解释一下您如何想象 sendCustomMessage 在所需行为中的用法?
    【解决方案2】:

    您可以使用原生闪亮包中的updateActionButton

    ui <- fluidPage(
      actionButton('someButton', ""),
      h3("Button value:"),
      verbatimTextOutput("buttonValue"),
      textInput("newLabel", "new Button Label:", value = "some label")
    )
    
    server <- function(input, output, session) {
    
      output$buttonValue <- renderPrint({
        input$someButton
      })
    
      observeEvent(input$newLabel, {
        updateActionButton(session, "someButton", label = input$newLabel)
      })
    }
    
    shinyApp(ui, server)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-08
      • 2021-12-02
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      • 2018-11-08
      • 2019-06-28
      • 2020-01-18
      相关资源
      最近更新 更多