单击后捕获actionButton的标签

时间:2015-03-31 18:39:57

标签: r shiny shiny-server

点击后可以捕获actionButton的标签吗?

想象一下,我的ui.R上有3个按钮,根据我点击的那个按钮,我想在服务器上执行不同的动作.R。

有一点需要注意,按钮是在server.R上动态创建的,带有动态标签(因此需要在点击时捕获标签)

由于

2 个答案:

答案 0 :(得分:1)

1)用户最后点击了什么按钮?

要回答这个问题,您可以使用observeEvent功能并使用reactiveValues功能设置变量。请确保更新您的库并使用最新版本的R (version 3.1.3),因为shiny取决于此版本。在Windows上工作,您可以按照如何更新here

的示例进行操作
rm(list = ls())
library(shiny)

ui =fluidPage(
  sidebarPanel(
    textInput("sample1", "Name1", value = "A"),
    textInput("sample2", "Name2", value = "B"),
    textInput("sample3", "Name3", value = "C"),
    div(style="display:inline-block",uiOutput("my_button1")),
    div(style="display:inline-block",uiOutput("my_button2")),
    div(style="display:inline-block",uiOutput("my_button3"))),
  mainPanel(textOutput("text1"))
)

server = function(input, output, session){

  output$my_button1 <- renderUI({actionButton("action1", label = input$sample1)})
  output$my_button2 <- renderUI({actionButton("action2", label = input$sample2)})
  output$my_button3 <- renderUI({actionButton("action3", label = input$sample3)})

  my_clicks <- reactiveValues(data = NULL)

  observeEvent(input$action1, {
    my_clicks$data <- input$sample1
  })

  observeEvent(input$action2, {
    my_clicks$data <- input$sample2
  })  

  observeEvent(input$action3, {
    my_clicks$data <- input$sample3
  })  

  output$text1 <- renderText({ 
    if (is.null(my_clicks$data)) return()
    my_clicks$data
  })
}
runApp(list(ui = ui, server = server))

2) 保存点击以进一步操作

以下是基于jdharrisonshinyStorage广告资源Shiny UI: Save the Changes in the Inputs工作的小例子。

rm(list = ls())
#devtools::install_github("johndharrison/shinyStorage")
library(shinyStorage)
library(shiny)

my_clicks <- NULL

ui =fluidPage(
  #
  addSS(),
  sidebarPanel(
    textInput("sample_text", "test", value = "0"),
    uiOutput("my_button")),
  mainPanel(uiOutput("text1"))
)

server = function(input, output, session){
  ss <- shinyStore(session = session)

  output$my_button <- renderUI({
    actionButton("action", label = input$sample_text)
  })

  observe({
    if(!is.null(input$sample_text)){
      if(input$sample_text != ""){
        ss$set("myVar", input$sample_text)
      }
    }
  })  

  output$text1 <- renderUI({
    input$action
    myVar <- ss$get("myVar")
    if(is.null(myVar)){
      textInput("text1", "You button Name")
    }else{
      textInput("text1", "You button Name", myVar)          
    }
  })
}
runApp(list(ui = ui, server = server))

答案 1 :(得分:1)

类似的东西吗?

library(shiny)

server <- function(input, session, output) {

  output$printLabel <- renderPrint({input$btnLabel})

}

ui <- fluidPage(

  actionButton("btn1", "Label1", 
               onclick = "Shiny.setInputValue('btnLabel', this.innerText);"),
  actionButton("btn2", "Label2", 
               onclick = "Shiny.setInputValue('btnLabel', this.innerText);"),

  verbatimTextOutput("printLabel")  

)

shinyApp(ui = ui, server = server)

enter image description here