HarmonyOS--ArkTS(3)--渲染控制(if/else,ForEach)

本文介绍了在HarmonyOS中如何使用条件渲染(if/else)和ForEach循环进行组件渲染,以及当数据量过大时如何利用List容器组件来优化显示。示例代码展示了如何在结构化组件中实现这些功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 文档地址:icon-default.png?t=N7T8https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/arkts-rendering-control-ifelse-0000001524177637-V3#section550519414249

if/else:条件渲染

@Entry
@Component
struct ViewA {
  @State count: number = 0;

  build() {
    Column() {
      Text(`count=${this.count}`)

      if (this.count > 1) {
        Text(`count 大于 1`)
    
      }else{
        Text(`啥也不是`)

   
    }
  }
}

ForEach:循环渲染


//三大参数
ForEach(
    //要遍历的数组
    arr: Array,
    //页面组件生成函数
    itemGenerator: (item: any, index?: number) => {
      
    },
    //键 生成函数--为数组每一项生成唯一标识,组件是否重新渲染的标准
    keyGenerator?: (item: any, index?: number): string => {
    }
)

用法 

@Entry
@Component
struct Parent {
  @State simpleList: Array<string> = ['one', 'two', 'three'];

  build() {
    Row() {
      Column() {
        ForEach(this.simpleList, (item: string) => {
          ChildItem({ item: item })
        }, (item: string) => item)
      }
      .width('100%')
      .height('100%')
    }
    .height('100%')
    .backgroundColor(0xF1F3F5)
  }
}

@Component
struct ChildItem {
  @Prop item: string;

  build() {
    Text(this.item)
      .fontSize(50)
  }
}

ForEach 循环 项过多 超出屏幕的时候  使用 容器组件 List 

HarmonyOS--容器组件 List-优快云博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值