用途:帮助开发者在 templ 中编写可复用的 UI 组件,支持带类型的 props、children 插槽与组合模式,适用于构建界面组件和组件库。技能建议采用渐进式披露:先用 Level 1 解决,复杂度升高时再参考更深层指引。
主要能力与用法:Level 1 组件清单要求定义单一用途的小组件,优先使用类型化 props(复杂 API 用 struct),通过 { children... } 支持组合,变体保持显式可预期,并抽取共享布局包装而非重复标记。示例中 Button 组件用 ButtonProps struct 定义 Label、Variant、Disabled,并在 templ 中渲染按钮。
Level 2 API 设计规则:保持小接口面,避免庞大 prop 列表;关键变体用枚举/常量而非自由字符串;组合优先,偏好 Card、Modal、Layout 等包装组件而非单体组件;组件只负责渲染,无隐藏副作用,数据处理交给 handler/loader;保持契约稳定,避免在无迁移情况下破坏 props 结构。
Level 3 可复用模式:Card 组件接收 title 并通过 children 填充正文;WithError 组件根据 error 是否为 nil 渲染错误信息或 children。
升级到其他技能:需要语法细节用 templ-syntax;需要 HTTP 路由/渲染用 templ-http;需要局部更新/交互用 templ-htmx。
参考资料:resources/foundations.md、resources/patterns.md、resources/testing-and-api.md;templ 组件指南 https://templ.guide/component-composition/ ;templ API 文档 https://pkg.go.dev/github.com/a-h/templ 。
限制:资料未提供安装命令、版本要求、收费信息、平台限制或具体性能效果,暂未提供。