且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在R Shiny数据表中添加自定义按钮?

更新时间:2023-12-01 14:34:28

除了操作之外,您不需要使用Javascript。您可以这样做:

You don't need to use Javascript, except for the action. You can do:

library(DT)
datatable(iris,
          extensions = 'Buttons',
          options = list(
            dom = 'Bfrtip',
            buttons = list(
              "copy",
              list(
                extend = "collection",
                text = 'test',
                action = DT::JS("function ( e, dt, node, config ) {
                                    alert( 'Button activated' );
                                }")
              )
            )
          )
)

要将某些内容从Javascript传递到闪亮的服务器,请使用 Shiny.setInputValue

To pass something from Javascript to the shiny server, use Shiny.setInputValue:

library(shiny)
library(DT)

ui <- basicPage(
  DTOutput("dtable")
)

server <- function(input, output, session){
  output$dtable <- renderDT(
    datatable(iris,
              extensions = 'Buttons',
              options = list(
                dom = 'Bfrtip',
                buttons = list(
                  "copy",
                  list(
                    extend = "collection",
                    text = 'test',
                    action = DT::JS("function ( e, dt, node, config ) {
                                      Shiny.setInputValue('test', true, {priority: 'event'});
                                   }")
                  )
                )
              )
    )
  )

  observeEvent(input$test, {
      print("hello")
  })
}

shinyApp(ui, server)