使用bslib Bootstrap4/5时navbarPage的列布局异常问题
问题原因
shinydashboard的box组件基于Bootstrap3网格系统设计,而Bootstrap4/5的网格类名、布局逻辑与Bootstrap3存在差异。使用bslib的Bootstrap4/5主题时,box自带的宽度控制参数会失效,导致所有盒子堆叠成单列。
解决方案
方案一:改用bslib原生card组件(推荐)
bslib的card是为Bootstrap4+量身打造的组件,完美适配bslib主题,搭配layout_columns或Bootstrap原生网格可轻松实现多行排列。
修改后的完整代码:
library(shiny) library(bslib) ui <- navbarPage( theme = bs_theme(version = 5), title = "Dynamic Cards", navbarMenu("Tab1", tabPanel("Item1", fluidPage( uiOutput("cards") ) ) ) ) server <- function(input, output) { output$cards <- renderUI({ # 使用layout_columns自动适配响应式布局,col_widths=6表示中等屏幕及以上每行2列 layout_columns( col_widths = 6, lapply(1:10, function(a) { card( title = paste0("Card ", a), plotOutput(paste0("plot_", a)) ) }) ) }) # 单独渲染每个绘图,避免renderPlot嵌套在renderUI中的潜在问题 lapply(1:10, function(a) { output[[paste0("plot_", a)]] <- renderPlot({ x <- 1:100 plot(x = x, y = x^a) }) }) } shinyApp(ui = ui, server = server)
方案二:保留shinydashboard的box,手动添加Bootstrap4/5网格类
通过Bootstrap4/5的column组件包裹每个box,显式指定列宽,让网格系统识别并排列盒子。
修改后的完整代码:
library(shiny) library(bslib) library(shinydashboard) ui <- navbarPage( theme = bs_theme(version = 4), title = "Dynamic Boxes", navbarMenu("Tab1", tabPanel("Item1", fluidPage( fluidRow( uiOutput("boxes") ) ) ) ) ) server <- function(input, output) { output$boxes <- renderUI({ lapply(1:10, function(a) { x <- 1:100 column( width = 6, # 每行显示2个盒子(12/6=2),可根据需求调整为4、3等 box( title = paste0("box ", a), renderPlot(plot(x = x, y = x^a)), width = 12 # 让box占满所在column的宽度 ) ) }) }) } shinyApp(ui = ui, server = server)
内容的提问来源于stack exchange,提问作者ashcrashbegash
相关产品推荐
相关产品推荐

