HarmonyOS鸿蒙Next中以下对象数组如何用objectlink修饰以达到数组内对象的属性刷新时刷新UI
HarmonyOS鸿蒙Next中以下对象数组如何用objectlink修饰以达到数组内对象的属性刷新时刷新UI
btnInfos: UIModel[] = [ { title: ‘天重复’, type: 0 }, { title: ‘周重复’, type: 1 }, { title: ‘月重复’, type: 2 }, { title: ‘年重复’, type: 3 }, ]
@Observed export class UIModel{ id?:string title?:string content?:string img?:Resource type?:number color?:ResourceColor option?:ResourceColor|boolean defaultImg?:Resource activeImg?:Resource }
更多关于HarmonyOS鸿蒙Next中以下对象数组如何用objectlink修饰以达到数组内对象的属性刷新时刷新UI的实战教程也可以访问 https://www.itying.com/category-93-b0.html
可以参考下文档:
@Observed
export class UIModel {
id?: string;
title?: string;
content?: string;
img?: Resource;
type?: number;
color?: ResourceColor;
option?: ResourceColor | boolean;
defaultImg?: Resource;
activeImg?: Resource;
constructor(type: number, title: string) {
this.title = title;
this.type = type;
}
}
@Component
@Entry
struct Index {
@State btnInfos: UIModel[] = [
new UIModel(0, '天重复'),
new UIModel(1, '周重复'),
new UIModel(2, '月重复'),
new UIModel(3, '年重复'),
];
build() {
Column() {
ForEach(this.btnInfos, (value: UIModel) => {
ObjectLinkChild({ test: value });
});
}
}
}
@Component
struct ObjectLinkChild {
@ObjectLink test: UIModel;
build() {
Text(`ObjectLinkChild testNum ${this.test.type}`)
.onClick(() => {
// 可以对ObjectLink装饰对象的属性赋值
if (this.test.type !== undefined) {
this.test.type = this.test.type + 1;
}
});
}
}
更多关于HarmonyOS鸿蒙Next中以下对象数组如何用objectlink修饰以达到数组内对象的属性刷新时刷新UI的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,使用ObjectLink
修饰对象数组时,可以通过@Observed
和@ObjectLink
装饰器来实现数组内对象属性刷新时UI的自动更新。
首先,使用@Observed
装饰器标记类,表示该类是可观察的。然后,在组件中使用@ObjectLink
装饰器来引用数组中的对象,这样当对象的属性发生变化时,UI会自动刷新。
示例代码如下:
@Observed
class Item {
name: string = '';
constructor(name: string) {
this.name = name;
}
}
@Entry
@Component
struct Index {
@State items: Item[] = [new Item('Item1'), new Item('Item2')];
build() {
Column() {
ForEach(this.items, (item: Item) => {
ItemView({ item: item })
})
}
}
}
@Component
struct ItemView {
@ObjectLink item: Item;
build() {
Text(this.item.name)
.onClick(() => {
this.item.name = 'Updated';
})
}
}
在这个示例中,Item
类被@Observed
装饰器标记为可观察的。Index
组件中的items
数组包含了Item
对象。ItemView
组件使用@ObjectLink
装饰器引用Item
对象,当Item
对象的name
属性被修改时,UI会自动刷新。
通过这种方式,可以实现数组内对象的属性刷新时UI的自动更新。
在HarmonyOS鸿蒙Next中,可以使用@Observed
和@ObjectLink
装饰器来实现数组内对象属性变化时UI的自动刷新。首先,使用@Observed
装饰类,然后在父组件中使用@ObjectLink
修饰数组中的对象。这样,当对象属性变化时,UI会自动更新。例如:
@Observed
class Item {
name: string;
constructor(name: string) {
this.name = name;
}
}
class ParentComponent {
@ObjectLink items: Item[];
updateItem(index: number, newName: string) {
this.items[index].name = newName;
}
}
这样,updateItem
方法修改items
数组中的对象属性时,UI会自动刷新。