问题场景现有一个数据Bean类型如下:export class TagBean { title: string = "" id: string = "" is_choose: boolean = false }用@State或@Link修饰该Bean的Array数组,如:@Link tagBeans: TagBean[]目前发现一个问题,在List()中的ForEach(this.tagBeans)内写Text(),背景设置为:.backgroundColor($r(item.is\_choose ? “颜色A” : “颜色B”))在点击事件中使tagBeans[index].is\_choose=true,无法实时更新UI状态但如果使用额外的string对象去记录点击id,判断(this.chooseIds.indexOf(item.id) \>= 0),就可以实现实时更新UI@ObjectLink和@Observed类装饰器用于在涉及嵌套对象或数组的场景中进行双向数据同步:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-observed-and-objectlink-V5demo参考如下import util from '@ohos.util'; @Observed class TagBean { key: string = util.generateRandomUUID(true); name: string; is_Choose: boolean; constructor(name: string, is_choose: boolean) { this.name = name; this.is_Choose = is_choose; } } @Component struct ViewListItem { @ObjectLink tagBean: TagBean; build() { ListItem() { Text(this.tagBean.name) .width('100%') .height(100) .fontSize(16) .textAlign(TextAlign.Center) .borderRadius(10) .backgroundColor(this.tagBean.is_Choose ? Color.White : Color.Red) }.onClick(() => { this.tagBean.is_Choose = !this.tagBean.is_Choose }) } } @Entry @Component struct ObservedDemo { @State tagBeans: Array<TagBean> = [ new TagBean('小红1', false), new TagBean('小红2', false), new TagBean('小红3', false), new TagBean('小红4', false), new TagBean('小红5', false), new TagBean('小红6', false), new TagBean('小红7', false), new TagBean('小红8', false), new TagBean('小红9', false), ] build() { Column() { List({ space: 20, initialIndex: 0 }) { ForEach(this.tagBeans, (item: TagBean) => { ViewListItem({ tagBean: item }) }, (item: TagBean) => item.key) } .listDirection(Axis.Vertical) .friction(0.6) .divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) .edgeEffect(EdgeEffect.Spring) .width('90%') } .backgroundColor(Color.Black) .width('100%') .height('100%') } }"
问题场景
现有一个数据Bean类型如下:
用@State或@Link修饰该Bean的Array数组,如:@Link tagBeans: TagBean[]
目前发现一个问题,在List()中的ForEach(this.tagBeans)内写Text(),背景设置为:.backgroundColor($r(item.is\_choose ? “颜色A” : “颜色B”))
在点击事件中使tagBeans[index].is\_choose=true,无法实时更新UI状态
但如果使用额外的string对象去记录点击id,判断(this.chooseIds.indexOf(item.id) \>= 0),就可以实现实时更新UI
@ObjectLink和@Observed类装饰器用于在涉及嵌套对象或数组的场景中进行双向数据同步:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-observed-and-objectlink-V5
demo参考如下