我有一个 Shiny 的应用程序,它使用 reactable 来显示任务的状态。状态列的信息采用颜色编码,数据使用 updateReactable()
进行更新。
最初颜色背景是正确的(例如红色表示打开,绿色表示完成),但是当我调用 updateReactable
时,背景颜色没有改变。
一个简单的解决方案是始终重新呈现表格,但我想保留用户输入(例如排序、筛选、页面选择等),因此我使用 updateReactable。
MWE 看起来像这样:
library(shiny)
library(reactable)
ui <- fluidPage(
reactableOutput("table"),
actionButton("go", "Go")
)
d <- data.frame(x = sample(letters, 10, replace = TRUE), status = "Open")
d[1, "status"] <- "Done"
cols_bg <- c("Open" = "red", "Done" = "green")
cols_font <- c("Open" = "black", "Done" = "white")
server <- function(input, output, session) {
# render this only once, update values later
output$table <- renderReactable({
reactable(d,
columns = list(
status = colDef(name = "Status",
style = function(value) {
list(background = cols_bg[[value]],
fontWeight = 600, color = cols_font[[value]])
})
)
)
})
# on button-click replace some values with Done and update table
observeEvent(input$go, {
ids <- sample(nrow(d), 0.7*nrow(d))
d$status[ids] <- "Done"
updateReactable("table", d)
})
}
shinyApp(ui, server)
点击之后看起来像这样:
请注意,所有“完成”字段都应为绿色。
最佳答案
根据 this article对于动态条件样式,我们需要提供一个 JS 函数:
library(shiny)
library(reactable)
ui <- fluidPage(reactableOutput("table"),
actionButton("go", "Go"))
d <- data.frame(x = sample(letters, 10, replace = TRUE), status = "Open")
d[1, "status"] <- "Done"
server <- function(input, output, session) {
output$table <- renderReactable({
reactable(d,
columns = list(status = colDef(
style = JS(
"function(rowInfo) {
if (rowInfo.values['status'] == 'Open') {
return { backgroundColor: 'red', color: 'black', fontWeight: 600}
} else if (rowInfo.values['status'] == 'Done') {
return { backgroundColor: 'green', color: 'white', fontWeight: 600 }
} else {
return { backgroundColor: 'grey', color: 'black', fontWeight: 600 }
}
}"
)
)))
})
# on button-click replace some values with Done and update table
observeEvent(input$go, {
ids <- sample(nrow(d), 0.7 * nrow(d))
d$status[ids] <- "Done"
updateReactable("table", d)
})
}
shinyApp(ui, server)
关于updateData 上可 react 的 R Shiny 条件颜色列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72768938/