HarmonyOS鸿蒙Next中如何让自定义类的成员变量的值发生变化时能刷新Swiper的UI
HarmonyOS鸿蒙Next中如何让自定义类的成员变量的值发生变化时能刷新Swiper的UI 页面UI组件FastNews,其中有一个@State修饰的成员变量dataList,它的类型是自定义类NewsDataClass的数组,FastNews中放置了UI组件Swiper,其数据来源是刚才所说的dataList(通过ForEach生成)。现在我需要修改数据来源中NewsDataClass的字段read的值来刷新局部的ui,应该怎么做?
@Observed
class NewsDataClass {
id: number
read: string
constructor(id: number, read: string) {
this.id = id
this.read = read;
}
}
@Entry
@Component
struct Page4 {
@State dataList: NewsDataClass[] = [];
private swiperController: SwiperController = new SwiperController()
aboutToAppear(): void {
this.dataList.push(new NewsDataClass(1, "111"))
this.dataList.push(new NewsDataClass(2, "222"))
this.dataList.push(new NewsDataClass(3, "333"))
}
build() {
Row() {
Column({ space: 10 }) {
Button('修改数据').onClick(() => {
for (let i = 0; i <= 2; i++) {
this.dataList[i].read = "xxx"
}
})
Swiper(this.swiperController) {
// 1、ObjectLink其实是监听item项,不能直接new一个新的Item项覆盖,否则监听对象就变了。这里建议直接去修改Item里面的属性值
ForEach(this.dataList, (item: NewsDataClass, index: number) => {
ChildComponent({ data: item })
.onClick(() => {
console.log('测试数据', JSON.stringify(this.dataList))
item.read += '00';
})
}, (item: NewsDataClass, index: number) => item.id.toString())
}
}.width('100%')
}.height('100%')
}
}
@Component
struct ChildComponent {
@ObjectLink @Watch('aa') data: NewsDataClass
aa() {
console.log('ObjectLink', JSON.stringify(this.data))
}
build() {
Row({ space: 5 }) {
Text(this.data.id + "").fontSize(16)
Text(this.data.read).fontSize(16)
.onAppear(() => {
console.info("appear:" + this.data.read)
})
}.margin({ left: 10, right: 10 }).width('90%').height(160)
}
}
更多关于HarmonyOS鸿蒙Next中如何让自定义类的成员变量的值发生变化时能刷新Swiper的UI的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,若要让自定义类的成员变量的值发生变化时刷新Swiper的UI,可以使用@Observed
和@ObjectLink
装饰器。首先,将自定义类标记为@Observed
,这样当类的成员变量发生变化时,系统会自动检测到变化。然后,在Swiper组件中使用@ObjectLink
来绑定该类的实例,这样当类的成员变量发生变化时,Swiper的UI会自动刷新。
例如,定义一个@Observed
类:
@Observed
class MyCustomClass {
value: string = '';
updateValue(newValue: string) {
this.value = newValue;
}
}
在Swiper组件中使用@ObjectLink
绑定该类的实例:
@Component
struct MySwiper {
@ObjectLink myCustomClass: MyCustomClass;
build() {
Swiper() {
Text(this.myCustomClass.value)
}
}
}
当MyCustomClass
的value
成员变量发生变化时,Swiper的UI会自动刷新。
在HarmonyOS鸿蒙Next中,当自定义类的成员变量值发生变化时,可以通过@Observed
和@ObjectLink
装饰器来实现UI的自动刷新。首先,使用@Observed
装饰自定义类,使其成为可观察对象;然后,在UI组件中使用@ObjectLink
绑定该类的实例,当成员变量变化时,Swiper的UI会自动刷新。