HarmonyOS掌上记账APP开发实践第29篇:条件渲染与 ForEach — 动态 UI 的构建策略

条件渲染与 ForEach --- 动态 UI 的构建策略

一、引言

动态 UI 是现代应用开发的核心需求------不同状态展示不同内容,列表数据动态填充。鸿蒙 ArkTS 提供了 if/else 条件渲染和 ForEach 循环渲染两种声明式渲染控制能力,帮助开发者高效构建动态界面。MoneyTrack 在账单详情成员信息展示、统计视图切换、账单列表渲染等场景中充分运用了这两种策略,实现了灵活且高性能的动态 UI 构建。

二、核心知识点

2.1 if/else 条件渲染完整语法

if/else 是 ArkTS 中最基本的条件渲染语法,根据布尔表达式的值决定是否创建或保留组件。与 show/hide 不同,if/else 会完全销毁和重建组件。ArkTS 支持完整的 if / else if / else 多分支结构:

typescript 复制代码
if (this.viewMode === ViewMode.CHART) {
  ChartSummary({ data: this.statisticsData })
} else if (this.viewMode === ViewMode.CALENDAR) {
  CalendarSummary({ data: this.statisticsData })
} else {
  ListSummary({ data: this.statisticsData })
}

关于三元运算符 :在 ArkTS 的 build() 方法中,condition ? A : B 三元运算符不能直接用于 UI 结构 ,只能用于属性值的条件赋值。条件渲染必须使用 if/else 语句块:

typescript 复制代码
build() {
  Column() {
    // 正确:if/else 用于组件分支
    if (this.isPremium) {
      PremiumBadge()
    }

    // 正确:三元运算符用于属性值
    Text('标题')
      .fontColor(this.isActive ? '#333333' : '#999999')
  }
}

2.2 条件渲染 vs visibility 属性

对比维度 if/else 条件渲染 visibility 属性控制
组件生命周期 销毁/重建 保留,仅隐藏
性能开销 创建+销毁有开销 零重建开销
适用场景 切换频繁、结构差异大 切换不频繁、结构相同
内存占用 不显示时不占用 始终占用
子组件状态 重建后丢失 保留

选择建议 :如果切换频率极高(如 Tab 切换),且组件创建成本较低,用 if/else 更合理;如果组件需要保留状态(如滚动位置),用 visibility 控制。

2.3 ForEach 列表渲染与 key 生成

ForEach 基于数组数据循环渲染组件列表,每个数组元素对应一个 UI 实例。其完整签名为:

typescript 复制代码
ForEach(
  arr: any[],                        // 数据源数组
  itemGenerator: (item, index) => void,  // 组件生成函数
  keyGenerator?: (item, index) => string  // key 生成函数(可选)
)

第三个参数 key 生成函数至关重要。它告诉框架如何唯一标识每个列表项,以便在数组变化时进行高效的 Diff 更新:

typescript 复制代码
// ✅ 推荐:使用唯一 ID 作为 key
ForEach(this.transactionList, (item: Transaction) => {
  ListItem() {
    TransactionCard({ transaction: item })
  }
}, (item: Transaction) => item.id.toString())

// ❌ 不推荐:使用索引作为 key(索引变化会导致组件复用错误)
ForEach(this.transactionList, (item: Transaction, index: number) => {
  ListItem() {
    TransactionCard({ transaction: item })
  }
}, (item: Transaction, index: number) => index.toString())

key 值不稳定的后果

  1. UI 错乱:框架复用错误的组件实例,导致列表项显示与实际数据不匹配。
  2. 性能下降:框架无法准确判断新增/删除项,导致全量重建。
  3. 动画异常:列表项增删动画可能错误地应用到其他项上。

2.4 ForEach 的 Diff 更新流程

#mermaid-svg-MEcnuSG5oBBzHl53{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-MEcnuSG5oBBzHl53 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-MEcnuSG5oBBzHl53 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-MEcnuSG5oBBzHl53 .error-icon{fill:#552222;}#mermaid-svg-MEcnuSG5oBBzHl53 .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-MEcnuSG5oBBzHl53 .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-MEcnuSG5oBBzHl53 .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-MEcnuSG5oBBzHl53 .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-MEcnuSG5oBBzHl53 .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-MEcnuSG5oBBzHl53 .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-MEcnuSG5oBBzHl53 .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-MEcnuSG5oBBzHl53 .marker{fill:#333333;stroke:#333333;}#mermaid-svg-MEcnuSG5oBBzHl53 .marker.cross{stroke:#333333;}#mermaid-svg-MEcnuSG5oBBzHl53 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-MEcnuSG5oBBzHl53 p{margin:0;}#mermaid-svg-MEcnuSG5oBBzHl53 .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-MEcnuSG5oBBzHl53 .cluster-label text{fill:#333;}#mermaid-svg-MEcnuSG5oBBzHl53 .cluster-label span{color:#333;}#mermaid-svg-MEcnuSG5oBBzHl53 .cluster-label span p{background-color:transparent;}#mermaid-svg-MEcnuSG5oBBzHl53 .label text,#mermaid-svg-MEcnuSG5oBBzHl53 span{fill:#333;color:#333;}#mermaid-svg-MEcnuSG5oBBzHl53 .node rect,#mermaid-svg-MEcnuSG5oBBzHl53 .node circle,#mermaid-svg-MEcnuSG5oBBzHl53 .node ellipse,#mermaid-svg-MEcnuSG5oBBzHl53 .node polygon,#mermaid-svg-MEcnuSG5oBBzHl53 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-MEcnuSG5oBBzHl53 .rough-node .label text,#mermaid-svg-MEcnuSG5oBBzHl53 .node .label text,#mermaid-svg-MEcnuSG5oBBzHl53 .image-shape .label,#mermaid-svg-MEcnuSG5oBBzHl53 .icon-shape .label{text-anchor:middle;}#mermaid-svg-MEcnuSG5oBBzHl53 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-MEcnuSG5oBBzHl53 .rough-node .label,#mermaid-svg-MEcnuSG5oBBzHl53 .node .label,#mermaid-svg-MEcnuSG5oBBzHl53 .image-shape .label,#mermaid-svg-MEcnuSG5oBBzHl53 .icon-shape .label{text-align:center;}#mermaid-svg-MEcnuSG5oBBzHl53 .node.clickable{cursor:pointer;}#mermaid-svg-MEcnuSG5oBBzHl53 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-MEcnuSG5oBBzHl53 .arrowheadPath{fill:#333333;}#mermaid-svg-MEcnuSG5oBBzHl53 .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-MEcnuSG5oBBzHl53 .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-MEcnuSG5oBBzHl53 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-MEcnuSG5oBBzHl53 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-MEcnuSG5oBBzHl53 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-MEcnuSG5oBBzHl53 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-MEcnuSG5oBBzHl53 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-MEcnuSG5oBBzHl53 .cluster text{fill:#333;}#mermaid-svg-MEcnuSG5oBBzHl53 .cluster span{color:#333;}#mermaid-svg-MEcnuSG5oBBzHl53 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-MEcnuSG5oBBzHl53 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-MEcnuSG5oBBzHl53 rect.text{fill:none;stroke-width:0;}#mermaid-svg-MEcnuSG5oBBzHl53 .icon-shape,#mermaid-svg-MEcnuSG5oBBzHl53 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-MEcnuSG5oBBzHl53 .icon-shape p,#mermaid-svg-MEcnuSG5oBBzHl53 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-MEcnuSG5oBBzHl53 .icon-shape .label rect,#mermaid-svg-MEcnuSG5oBBzHl53 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-MEcnuSG5oBBzHl53 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-MEcnuSG5oBBzHl53 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-MEcnuSG5oBBzHl53 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 是

数据源数组变化
keyGenerator 是否提供?
基于 key 做 Diff 比对
基于索引位置比对
匹配成功 → 更新已有组件属性
未匹配 → 创建新组件 / 删除旧组件
新增项 → 尾部追加
删除/插入 → 后续组件整体重建
增量更新,性能最优
性能一般

当提供稳定的 key 时,框架执行基于 key 的 Diff 算法,精确识别新增、删除和移动的项,做到最小化 DOM 操作。不使用 key 时,框架退化为索引比对,在列表中间插入或删除元素会导致后续所有组件重建。

2.5 LazyForEach 简要说明

对于超长列表(数百条以上),ForEach 会一次性创建所有组件实例,可能导致内存不足。LazyForEach 是懒加载版本,仅渲染当前可见区域的列表项,滚动时按需创建和回收组件:

typescript 复制代码
LazyForEach(this.dataSource, (item: Transaction) => {
  ListItem() {
    TransactionCard({ transaction: item })
  }
}, (item: Transaction) => item.id.toString())

LazyForEach 需要配合实现了 IDataSource 接口的数据源类使用,适用于无限滚动、消息列表等大数据量场景。

三、项目代码案例

3.1 BillDetailPage 中成员信息条件渲染

products/entry/src/main/ets/views/bill/BillDetailPage.ets 中,根据账单类型(个人/共享)条件渲染成员信息区域:

  • 个人账单:展示"仅自己可见"提示
  • 家庭账单:展示参与成员的头像列表
typescript 复制代码
if (this.billType === BillType.SHARED) {
  // 渲染成员头像列表
  Row() {
    ForEach(this.memberList, (member: MemberModel) => {
      Image(member.avatar).width(32).height(32).borderRadius(16)
    }, (member: MemberModel) => member.id.toString())
  }
} else {
  // 渲染个人标签
  Text('个人账单').fontSize(14).fontColor('#999')
}

3.2 StatisticsView 中 ChartSummary/CalendarSummary 切换

在统计页面,根据用户选择的视图模式条件渲染:

  • isChartViewtrue 时渲染 ChartSummary 组件(图表报表)
  • isChartViewfalse 时渲染 CalendarSummary 组件(日历视图)
  • 两种视图的数据结构不同,采用条件渲染完全隔离两种 UI 实现

3.3 ForEach 渲染账单列表

在首页和账单页面中,DailyBillGroupBillCard 通过 ForEach 渲染每日账单分组和具体账单项,每个列表项使用 item.id 作为稳定 key,保证列表更新时的性能。

四、最佳实践总结

  1. 始终提供稳定的 key:使用数据库 ID 作为 key,绝不使用索引。
  2. 条件渲染 vs visibility :结构差异大时用 if/else,切换需要保留状态时用 visibility
  3. 避免复杂条件表达式build() 中的条件逻辑应简洁明了,复杂逻辑提取到计算属性。
  4. 大数据量用 LazyForEach:超过 100 条数据时,优先考虑懒加载方案。
  5. 三元运算符仅用于属性值 :不要试图在 build() 中用三元表达式替代 if/else

五、参考文档

相关推荐
春卷同学1 小时前
HarmonyOS掌上记账APP开发实践第22篇:Scroll + List 虚拟列表 — 长列表性能优化全攻略
性能优化·list·harmonyos
不羁的木木1 小时前
《HarmonyOS技术精讲-NearLink Kit(星闪服务)》第4篇:广播通信——一对多广播应用实现
华为·harmonyos
w139548564221 小时前
鸿蒙应用开发实战【91】— 完整功能串联从添加到换绑的全链路
华为·harmonyos·鸿蒙系统
2501_919749031 小时前
华为鸿蒙免费训练口才APP—小羊口才
华为·harmonyos
木木子222 小时前
# [特殊字符] 画画模拟器 — 鸿蒙ArkTS完整技术解析
华为·harmonyos
Helen_cai2 小时前
OpenHarmony 图片选择 & 相册相机工具封装 ImagePickerUtil(API23)
数码相机·华为·harmonyos
小小测试开发2 小时前
Midscene.js:14K Stars 视驱 UI 自动化框架,用截图替代 DOM 选择器写测试
javascript·ui·自动化
不吃辣4902 小时前
从0-1学习导航页面布局优化和搭建
ui·平面·前端框架
AD022711 小时前
22-平板上页面被拉扁-用断点布局和资源覆盖做一多适配
harmonyos·arkts·鸿蒙开发