三亩地 三亩地SAN MU DI · CODE DIARY
ARTICLE DETAIL

日记详情

真实记录编程学习的某一天,欢迎挑你感兴趣的翻一翻。

第5章 ArkUI(下)

第5章 ArkUI(下)

在UI开发中,开发者经常会遇到编写相似或重复代码的情况,以确保整体外观和样式的一致性。ArkUI提供了渲染语句、组件的导出和导入、组件代码复用等功能,可以帮助开发者减少编写相似或重复代码的情况,同时确保整体外观和样式的一致性。本章将对ArkUI进阶知识进行详细讲解。

5.1 渲染语句

5.1.1 条件渲染语句

在开发中,有时需要根据某个条件决定是否渲染某个组件,此时可以使用条件渲染语句。条件渲染语句包括if语句、if…else语句、if…else if…else语句。

下面以if语句为例演示条件渲染语句的使用方法。

@Entry @Component struct IfPage {  @State showImg: boolean = true;  build() {    Row() {      Column() {        Checkbox()         .select(this.showImg)         .onChange(isON => {            this.showImg = isON;         })        if (this.showImg) {          Image($r('app.media.coin'))           .width(150)           .height(150)       }     }     .width('100%')   }   .height('100%') } }

5.1.2 循环渲染语句

在开发中,有时需要渲染一批相同的组件。对于这样的需求,可以通过循环渲染语句来实现,从而减少重复的组件代码。

循环渲染语句主要是通过ForEach()函数实现的。

使用ForEach()函数可以基于数组进行循环渲染,在渲染过程中,系统会为每个数组元素生成一个唯一且持久的键,用于标识对应的组件。

当这个键发生变化时,ArkUI将视为该数组元素已被替换或修改,并会基于新的键创建一个新的组件。

ForEach()函数的语法格式如下。 ForEach( arr: Array, itemGenerator: (item: 类型, index?: number) => void, keyGenerator?: (item: 类型, index?: number): string => string )

参数arr表示数据源,它是一个数组。 参数itemGenerator表示组件生成函数。 参数keyGenerator表示键生成函数。 在这两个函数中,item参数表示数组中元素的值,index参数表示数组中元素的索引。

itemGenerator表示的函数会为数组中的每个元素创建组件,该函数中可以包含条件渲染语句,也可以在条件渲染语句中使用ForEach()函数。

在用keyGenerator参数表示的函数中可以自定义键的生成规则。如果开发者没有定义keyGenerator表示的函数,则ArkUI会使用默认的键生成函数,相当于如下代码。

(item: 类型, index: number) => index + '__' + JSON.stringify(item);

下面通过代码演示ForEach()函数的使用方法。

interface GoodsItem {  id: number;  goods_name: string;  goods_img: Resource;  goods_price: number;  goods_count: number; } @Entry @Component struct ForEachPage {  @State list: GoodsItem[] = [{    id: 1,    goods_name: 'Vue.js前端开发实战(第2版)',    goods_img: $r('app.media.vue'),    goods_price: 49.8,    goods_count: 1, }, {    id: 2,    goods_name: '软件测试(第2版)',    goods_img: $r('app.media.test'),    goods_price: 49.8,    goods_count: 1, }, {    id: 3,    goods_name: 'PHP+MySQL动态网站开发',    goods_img:  $r('app.media.mysql'),    goods_price: 49.8,    goods_count: 1, }, {    id: 4,    goods_name: 'Python数据预处理',    goods_img: $r('app.media.python'),    goods_price: 39.8,    goods_count: 1, }];  build() {    List() {      ForEach(this.list, (item: GoodsItem) => {        ListItem() {          Row({ space: 10 }) {            Image(item.goods_img)             .borderRadius(8)             .width(120)             .height(200)            Column() {              Text(item.goods_name)               .fontWeight(FontWeight.Bold)              Text('¥' + item.goods_price.toString() )               .fontColor(Color.Red)               .fontWeight(FontWeight.Bold)           }           .padding({ top: 5, bottom: 5 })           .alignItems(HorizontalAlign.Start)           .justifyContent(FlexAlign.SpaceBetween)           .height(200)           .layoutWeight(1)         } &nb
← 返回列表