import { util } from '@kit.ArkTS';
/** * 三级数据结构 */@ObservedV2 class GrandsonInfo { @Trace content: string = "";
}
/** * 二级数据结构 */@ObservedV2 class ChildInfo { @Trace index: number; @Trace grandsonInfo: GrandsonInfo;
constructor(index: number, content: string) { this.index = index; this.grandsonInfo = new GrandsonInfo(); this.grandsonInfo.content = content; }}
/** * 一级数据结构 */@ObservedV2 class ItemInfo { key: string = util.generateRandomUUID(true); @Trace name: string; @Trace icon: Resource; @Trace childInfo: ChildInfo; @Trace select: boolean;
constructor(name: string, icon: Resource, index: number, content: string) { this.name = name; this.icon = icon; this.childInfo = new ChildInfo(index, content); this.select = false; }}
/** * 多层嵌套刷新渲染 */@Entry@Componentstruct ObservedPage { private TAG: string = "ObservedPage"; // @State无法混用,运行时报错 // @State mListData: Array<ItemInfo> = []; mListData: Array<ItemInfo> = [];
aboutToAppear(): void { this.mListData.push(new ItemInfo('游戏', $r("app.media.iconA"), 1, "鹅厂1")); this.mListData.push(new ItemInfo('游戏', $r("app.media.iconB"), 2, "鹅厂2")); this.mListData.push(new ItemInfo('游戏', $r("app.media.iconA"), 3, "鹅厂3")); this.mListData.push(new ItemInfo('游戏', $r("app.media.iconB"), 4, "鹅厂4")); this.mListData.push(new ItemInfo('游戏', $r("app.media.iconA"), 5, "鹅厂5")); this.mListData.push(new ItemInfo('游戏', $r("app.media.iconB"), 6, "鹅厂6")); }
build() { List() { ForEach(this.mListData, (item: ItemInfo, index: number) => { ListItem() { Row() { Image(this.item.icon) .width(px2vp(200)) .height(px2vp(200))
Text(this.item.name + "(" + this.item.childInfo.index + ")" + " [ " + this.item.childInfo.grandsonInfo.content + " ] ") .fontSize(px2fp(52))
Blank() if(this.isLog(this.item, this.index)){ if(this.item.select){ Image($r("app.media.icon_check")) .size({ width: px2vp(72), height: px2vp(72) }) } } } .width('100%') .justifyContent(FlexAlign.Start) .onClick(()=>{ this.item.select = !this.item.select; if(this.item.select){ // 使用很方便,只需要直接改变item数据的任意层级属性值,变化就会同步刷新 this.item.childInfo.index = 666; this.item.childInfo.grandsonInfo.content = "鹅厂23333" }else{ this.item.childInfo.index = this.index; this.item.childInfo.grandsonInfo.content = "鹅厂" + this.index; } console.log(this.TAG, " ItemView onClick: " + this.index + " item.select: " + this.item.select); }) } }, (item: ItemInfo) => JSON.stringify(item)) } .width("100%") .height("100%") .padding({ left: px2vp(60), right: px2vp(60) }) }}
评论