我已经发现 R Shiny (1.9.1) 的 DT(稳定:0.33,开发:0.33.1)存在问题,可以通过一些 Javascript 解决。
具体来说,当使用多个选项卡时(请参见下面的表示),如果使用
DT::replaceData()
在单击按钮的不同选项卡集上使用滚动条更新 DT 表,则第一个渲染将是正确的:
但是第二次单击按钮时,标题在左侧“挤压”在一起:这似乎仅在启用任何形式的滚动(在本例中为强制功能)时才成为问题,无论是否使用滚动器扩展(和分页)。 不使用滚动条不会导致此行为。
代表:
library(shiny)
library(DT)
# doesn't work
ui = fluidPage(
tabsetPanel(
tabPanel("button",
actionButton("change", "Change")
),
tabPanel("table",
DT::dataTableOutput("table"))
)
)
# works
# ui = fluidPage(
#
# tabsetPanel(
# tabPanel("button and table in one tab",
# tags$br(),
# actionButton("change", "Change"),
# tags$br(),
# DT::dataTableOutput("table"))
# )
#
# )
server = function(input, output, session) {
cars_plus = mtcars
cars_plus$new = sample(100, 1)
rvs = reactiveValues(
cars = cars_plus
)
table_proxy = DT::dataTableProxy("table")
output$table = DT::renderDataTable(server = T, {
DT::datatable(isolate(rvs$cars),
rownames = FALSE,
extensions = c('Buttons'),
options=list(
buttons = list(
list(extend = 'colvis', text = 'Choose visible columns')
),
dom = '<"top"B>rt<"bottom">i',
scrollY = '200',
paging = F
)
)
})
observeEvent(input$change,{
dat = rvs$cars
changer = sample(100, 1)
dat[3, "new"] = changer
rvs$cars = dat
DT::replaceData(table_proxy, dat, rownames = F, resetPaging = F, clearSelection = "none")
})
}
shinyApp(ui, server)
scrollY
存在一些问题。您可以通过在
shown.bs.tab
上添加一个事件处理程序来避免这种情况,该事件处理程序将 width
的
dataTable
重置为
100%
并调用
columns.adjust()
:
$(document).ready(function() {
$('a[data-toggle="tab"]').on( 'shown.bs.tab', function (e) {
$($.fn.dataTable.tables( true ) ).css('width', '100%');
$($.fn.dataTable.tables( true ) ).DataTable().columns.adjust().draw();
});
});
library(shiny)
library(DT)
ui = fluidPage(
tags$head(tags$script(HTML(
"$(document).ready(function() {
$('a[data-toggle=\"tab\"]').on( 'shown.bs.tab', function (e) {
$($.fn.dataTable.tables( true ) ).css('width', '100%');
$($.fn.dataTable.tables( true ) ).DataTable().columns.adjust().draw();
});
});"
))),
tabsetPanel(
tabPanel("button",
actionButton("change", "Change")
),
tabPanel("table",
DT::dataTableOutput("table"))
)
)
server = function(input, output, session) {
cars_plus = mtcars
cars_plus$new = sample(100, 1)
rvs = reactiveValues(
cars = cars_plus
)
table_proxy = DT::dataTableProxy("table")
output$table = DT::renderDataTable(server = T, {
DT::datatable(isolate(rvs$cars),
rownames = FALSE,
extensions = c('Buttons'),
options=list(
buttons = list(
list(extend = 'colvis', text = 'Choose visible columns')
),
dom = '<"top"B>rt<"bottom">i',
scrollY = '200',
paging = F
)
)
})
observeEvent(input$change,{
dat = rvs$cars
changer = sample(100, 1)
dat[3, "new"] = changer
rvs$cars = dat
DT::replaceData(table_proxy, dat, rownames = F, resetPaging = F, clearSelection = "none")
})
}
shinyApp(ui, server)