HarmonyOS应用开发实战:猫猫大作战-@Builder 装饰器与自定义组件

发布时间:2026/7/29 15:15:41

HarmonyOS应用开发实战:猫猫大作战-@Builder 装饰器与自定义组件 前言Builder是 ArkUI 中用于自定义 UI 构建函数的装饰器。在「猫猫大作战」中Builder用于封装按钮样式、游戏面板、猫咪卡片等可复用的 UI 片段。一、Builder 基础Builder MainMenuButton(text: string, onClick: () void) { Button(text) .width(80%).height(48) .fontSize(17).fontWeight(FontWeight.Bold) .fontColor(#FFFFFF) .backgroundColor(#2ECC71) .borderRadius(24) .onClick(() onClick()) } // 使用 Column() { MainMenuButton(开始游戏, () this.startGame()) MainMenuButton(游戏设置, () this.openSettings()) MainMenuButton(排行榜, () this.showRank()) }二、Builder 参数Builder ScoreDisplay(score: number, label: string, color: string) { Column() { Text(label).fontSize(12).fontColor(#95A5A6) Text(${score}) .fontSize(28).fontWeight(FontWeight.Bold) .fontColor(color) } .alignItems(HorizontalAlign.Center) }三、Builder vs Component特性BuilderComponent定义函数struct状态管理无独立状态有 State复用性适合小片段适合大组件传参函数参数Prop/Link四、游戏中的应用// 游戏 HUD 组件化 Builder GameHUD(score: number, combo: number, time: number) { Row() { ScoreDisplay(score, 得分, #E74C3C) ScoreDisplay(combo, 连击, #F39C12) ScoreDisplay(time, 时间, #95A5A6) } .width(100%) .padding(16) .justifyContent(FlexAlign.SpaceEvenly) }五、最佳实践参数化将颜色、大小等可变的属性作为参数传入单一职责每个 Builder 只封装一个 UI 功能与 Component 配合小片段用 Builder大模块用 Component总结Builder装饰自定义 UI 函数参数化复用布局片段。核心要点可传参的 UI 函数、 适合按钮/面板等小片段、 与 Component 配合使用。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源Builder 官方文档第 103 篇stat-item第 105 篇wrapBuilder第 106 篇Styles

相关新闻