我正在使用 R闪亮、bslib 和 DT 构建一个应用程序。
在 Bootstrap 的旧版本中,使用 formatStyle 函数可以轻松更改 DT 的样式(包括某些行的颜色)。 但是,对于新应用程序,我们使用 bslib 和 bootstrap 5,即使 github 上的用户说应该解决该问题,但该功能似乎已损坏(https://github.com/rstudio/DT/issues/1102)。 在使用不同版本的 DT 和 bslib(发布版和开发版)进行一些测试后,我仍然无法使其工作。
是否有另一种方法可以使用 bslib 和 bootstrap 5 动态更改 DT 的某些组件的颜色?
library(bslib)
library(DT)
ui <- function(id) {
card(
DT::dataTableOutpu("repeatsTable")
}
server <- function(id) ({
output$repeatsTable <- DT::renderDataTable({
repeatsDT <- DT::datatable(repeatsData(),
extensions = c("Buttons", "ColReorder"),
selection = "single",
options = list(
dom = "Bfrtip",
buttons = list(I("colvis")),
scrollX = TRUE,
colReorder = TRUE
)
) %>%
formatStyle("isPathogenic", target = "row", color = styleEqual(c(0, 1, 2), c("black", "orange", "red")))
})
})
编辑:添加可以自行运行的虚拟工作代码(来自上面的链接)
library(shiny)
library(dplyr)
library(DT)
library(bslib)
ui <- bslib::page_sidebar(
DT::DTOutput("tab1")
)
server <- function(input, output) {
output$tab1 <- DT::renderDT({
mtcars %>%
head() %>%
# this line works
#DT::datatable(style = "default") %>%
DT::datatable() %>%
DT::formatStyle(
columns = "mpg",
target = "row",
color = DT::styleEqual(c(21), "white"),
backgroundColor = DT::styleEqual(c(21), "#4d4d4d"),
)
})
}
shinyApp(ui = ui, server = server)
问题是单元格也有一些 CSS 属性,并且它们的优先级高于行的 CSS 属性。解决方法是取消设置单元格的 CSS 属性:
output$tab1 <- DT::renderDT({
mtcars %>%
head() %>%
DT::datatable() %>%
DT::formatStyle(
columns = 1:ncol(mtcars),
target = "cell",
color = JS("\"unset\""),
backgroundColor = JS("\"unset\"")
) %>%
DT::formatStyle(
columns = "mpg",
target = "row",
color = DT::styleEqual(c(21), "white"),
backgroundColor = DT::styleEqual(c(21), "orange")
)
})