如何区分按钮在R/Shiny可响应的javascript回调?



从可操作的文档(链接中提供了交互式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'drowInfocolInfo,找不到任何似乎有助于识别这两个按钮。我想拥有它,这样我就可以同时返回:

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

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

从JS方面,所以我可以在r单独处理它们。任何帮助是感激的!

如果您只想获得行索引,您可以这样做:

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
)
)
)

最新更新