簡體   English   中英

R Shiny 中 DT::datatable() 中凍結標頭問題的解決方法

[英]Workaround for issues with freezing header in DT::datatable() in R Shiny

我在 R Shiny 應用程序中使用 DT::datatable() 來呈現一個表,其中表頭和第一列是固定的。 我的應用程序有多個選項卡。 我嘗試了兩種不同的方法,但都存在使它們無法使用的錯誤。 我知道已經報告了這些問題,但我想知道是否有人知道適用於我的情況的解決方法。

方法#1:scrollY

在這里,我在選項中設置了scrollY = "500px" 問題是,當我將條目數更改為 10 以外的內容時,當我滾動到底部時,第一列與其他列未對齊。

require(shiny)
require(DT)

shinyApp(
  ui = tabsetPanel(
    tabPanel(
      title = "Tab 1",
      fluidPage(
        DTOutput("table1")
      )
    ),
    tabPanel(
      title = "Tab 2",
      fluidPage(
        plotOutput("myPlot"),
        DTOutput("table2")
      )
    )
  ),
  server = function(input, output, session) {
    
    output$table1 <- DT::renderDataTable({
      
      myData <- cbind(iris, iris, iris, iris)
      colnames(myData) <- paste0("Column ", 1:ncol(myData))
      
      DT::datatable(
        data = myData, 
        extensions = "FixedColumns", 
        rownames = F,
        options = list(
          scrollX = T, 
          scrollY = "500px",
          fixedColumns = list(leftColumns = 1)
        ) 
      ) 
    })
    
    output$myPlot <- renderPlot({
      plot(1:10, 1:10)
    })
    
    output$table2 <- DT::renderDataTable({
      DT::datatable(iris)
    })
    
  }
)

在此處輸入圖片說明

方法#2:FixedHeader 擴展

這里我使用 FixedHeader 擴展並在選項中設置fixedHeader = T 這避免了方法#1 的問題,但它有一個更嚴重的問題。 表格中的固定標題出現在其他選項卡上。 在此示例中,如果我向下滾動選項卡 1 上的表格,標題將按預期保持固定,但是當我切換到選項卡 2 並向下滾動時,選項卡 1 上的表格中的固定標題出現在選項卡 2 上。

require(shiny)
require(DT)

shinyApp(
  ui = tabsetPanel(
    tabPanel(
      title = "Tab 1",
      fluidPage(
        DTOutput("table1")
      )
    ),
    tabPanel(
      title = "Tab 2",
      fluidPage(
        plotOutput("myPlot"),
        DTOutput("table2")
      )
    )
  ),
  server = function(input, output, session) {
    
    output$table1 <- DT::renderDataTable({
      
      myData <- cbind(iris, iris, iris, iris)
      colnames(myData) <- paste0("Column ", 1:ncol(myData))
      
      DT::datatable(
        data = myData, 
        extensions = c("FixedColumns", "FixedHeader"), 
        rownames = F,
        options = list(
          scrollX = T, 
          fixedHeader = T,
          fixedColumns = list(leftColumns = 1)
        ) 
      ) 
    })
    
    output$myPlot <- renderPlot({
      plot(1:10, 1:10)
    })
    
    output$table2 <- DT::renderDataTable({
      DT::datatable(iris)
    })
    
  }
)

在此處輸入圖片說明

將 DT 從 0.19 版更新到 0.20 版(11/15/2021 發布)修復了該問題,因此方法 #1 可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM