3

reactable文档中获取这个示例(链接中提供的交互式 Shiny 示例):

data <- cbind(
  MASS::Cars93[1:5, c("Manufacturer", "Model", "Type", "Price")],
  details = NA
)

reactable(
  data,
  columns = list(
    # Render a "show details" button in the last column of the table.
    # This button won't do anything by itself, but will trigger the custom
    # click action on the column.
    details = colDef(
      name = "",
      sortable = FALSE,
      cell = function() htmltools::tags$button("Show details")
    )
  ),
  onClick = JS("function(rowInfo, colInfo) {
    // Only handle click events on the 'details' column
    if (colInfo.id !== 'details') {
      return
    }

    // Display an alert dialog with details for the row
    window.alert('Details for row ' + rowInfo.index + ':\\n' + JSON.stringify(rowInfo.row, null, 2))

    // Send the click event to Shiny, which will be available in input$show_details
    // Note that the row index starts at 0 in JavaScript, so we add 1
    if (window.Shiny) {
      Shiny.setInputValue('show_details', { index: rowInfo.index + 1 }, { priority: 'event' })
    }
  }")
)

我想在每个details列单元格中包含 2 个按钮,我可以通过将cell定义更改为:

                             cell = function() {
                              a <- htmltools::tags$button("Approve")
                              b <- htmltools::tags$button("Decline")
                              return(list(a,b))
                             }

但是如何区分JS() onClick()功能内的批准/拒绝按钮呢?我可以传递另一个参数来赋予我这种能力吗?我console.log既想rowInfocolInfo找不到任何似乎有助于识别这两个按钮的东西。我想拥有它,以便我可以同时返回:

Shiny.setInputValue('approve_button_click', ...)

Shiny.setInputValue('decline_button_click',...)

从 JS 方面,所以我可以在 R 中单独处理它们。任何帮助表示赞赏!

4

1 回答 1

1

如果您只想获取行索引,您可以执行以下操作:

library(htmltools)

details = colDef(
  name = "",
  sortable = FALSE,
  cell = function(value, rowIndex, colName){
    as.character(tags$div(
      tags$button("Approve", onclick=sprintf('alert("approve - %d")', rowIndex)),
      tags$button("Decline", onclick=sprintf('alert("decline - %d")', rowIndex))
    ))
  },
  html = TRUE
)

在闪亮:

reactable(
  data,
  columns = list(
    details = colDef(
      name = "",
      sortable = FALSE,
      cell = function(value, rowIndex, colName){
        as.character(tags$div(
          tags$button(
            "Approve", 
            onclick = 
              sprintf(
                'Shiny.setInputValue("approve", %d, {priority: "event"})', 
                rowIndex
              )
          ),
          tags$button(
            "Decline", 
            onclick = 
              sprintf(
                'Shiny.setInputValue("decline", %d, {priority: "event"})', 
                rowIndex
              )
          )
        ))
      },
      html = TRUE
    )
  )
)
于 2021-08-24T08:59:31.130 回答