用途:在 Rails 8 项目中以测试驱动开发(TDD)方式创建 ViewComponent,用于构建可复用、可单元测试的 UI 组件,或把复杂 partial 抽取为组件。
主要能力:ViewComponent 是 Ruby 对象,比 partial 更快(无 partial 查找),无需完整请求周期即可单元测试,可用 Ruby 封装视图逻辑,并通过显式接口实现类型安全。资料给出 TDD 工作流:先写组件测试(RED)、运行失败、生成组件骨架、实现组件、运行通过(GREEN)、按需添加变体或插槽。
常见模式:基础组件(如 CardComponent,含 title/subtitle 与 content 块);状态徽章(BadgeComponent 用 VARIANTS 常量映射 success/warning/error/info/neutral 样式);带插槽组件(renders_one :header、renders_one :footer、renders_many :actions);集合组件(with_collection_parameter :event,配合 with_collection 渲染);模态框组件(renders_one :trigger/:title/:footer,按 size 返回尺寸类)。
使用方式:组件继承 ApplicationComponent(继承 ViewComponent::Base,可包含 TagHelper、NumberHelper 等);在视图中用 render BadgeComponent.new(...) 渲染,带块或插槽时用 render CardComponent.new do |card| ... end,集合用 render EventCardComponent.with_collection(@events)。测试继承 ViewComponent::TestCase,使用 render_inline 与 assert_selector/assert_text。开发预览继承 ViewComponent::Preview,访问 http://localhost:3000/rails/view_components 查看。
适用场景:需要复用 UI 元素、抽取复杂 partial、为视图逻辑编写单元测试的 Rails 项目。
限制:资料未提供安装命令、版本依赖、性能基准数据、收费信息及与其他组件方案的对比;示例基于 Rails 8 与 Tailwind 风格类名,实际使用需按项目环境调整。