如何用Rails ViewComponent实现动态传递对象的多行排列?
问题解决:Rails ViewComponent + TailwindCSS 组件换行布局
问题
在Rails应用中使用TailwindCSS和ViewComponent,通过哈希数组传递数据渲染多个项目组件时,所有组件挤在同一行出现重叠,需要实现空间不足时自动换行,同时保持组件间水平间距space-x-4。
解决方案
核心是给包裹组件的容器添加flex-wrap类(Tailwind默认flex容器不换行),同时可添加垂直间距类space-y-4优化换行后的布局,另外可给单个组件加flex-shrink-0避免被压缩变形。
修改步骤:
- 给渲染组件的外层div添加
flex-wrap和space-y-4类 - (可选)给单个组件容器添加
flex-shrink-0类,防止组件被挤压变形
修改后的代码
整体区域的HTML与组件代码
<section class="flex bg-Ghost-White px-48"> <div class="flex bg-Ghost-White px-48"> <div class="basis-[40%] flex flex-col"> <p class="text-Eerie-Black text-[30px] font-bold tracking-[-0.75px] leading-[34px]">Who have we helped?</p> <p class="text-Outer-Space text-[22px] font-normal tracking-[-0.55px] leading-[32px]">We take pride in providing help to people around the world.</p> </div> <!-- 新增flex-wrap实现换行,space-y-4添加垂直间距 --> <div class="flex flex-wrap basis-[60%] space-x-4 space-y-4 bg-Ghost-White"> <%= render Homepage::Projects::Project::Component.with_collection(@projects) %> </div> </div> </section>
module Homepage module Projects class Component < ViewComponent::Base def initialize @projects = [{ title: "Water Well", image: "water-well.svg" }, { title: "Helping Children", image: "helping-children.svg" }, { title: "Eid", image: "eid.svg" }, { title: "Ramadan", image: "ramadan.svg" }, { title: "Orphans", image: "orphans.svg" }, { title: "Emergencies", image: "emergencies.svg" }, { title: "UK Projects", image: "uk-projects.svg" }, { title: "Mosque Builds", image: "mosque-builds.svg" }, { title: "Homeless", image: "homeless.svg" }] end end end end
单个组件的代码(可选优化)
<!-- 添加flex-shrink-0防止组件被压缩变形 --> <div class="flex items-center space-x-2 p-4 bg-White flex-shrink-0"> <%= image_tag @project[:image], class: "w-[45px] h-[45px]", alt: "" %> <p class="whitespace-nowrap"><%= @project[:title] %></p> </div>
module Homepage module Projects module Project class Component < ViewComponent::Base with_collection_parameter :project def initialize(project:) @project = project end end end end end
关键类说明
flex-wrap:让flex容器内的元素在空间不足时自动换行space-y-4:给换行后的组件添加垂直间距,提升布局美观度flex-shrink-0:锁定组件宽度,避免因容器空间不足被挤压变形(若需要组件自适应宽度可省略)
内容的提问来源于stack exchange,提问作者Fuaad
相关产品推荐
相关产品推荐

