HarmonyOS 鸿蒙Next中属性的值变化如何刷新UI
HarmonyOS 鸿蒙Next中属性的值变化如何刷新UI
class中某个属性的值变化,如何刷新UI?
-
@Observed可以实现这种刷新UI吗?
-
通过代理对象的方式也可以刷新,但是我觉得比较麻烦(import { plainToInstance } from ‘class-transformer’)
-
还有下面这种办法,修改之后,重新赋值
-
还有其他办法能实现这种需求吗?
@Entry
@Component
struct MoreViewPage {
@State list: test[] = [new test(0, '壹'), new test(1, '贰')]
build() {
Column() {
ForEach(this.list, (item: test) => {
Row() {
Text(`${item.id}---${item.name}`)
}
})
Text('点击').fontSize(20).onClick(() => {
this.list[0].name = '刘小宇'
})
}
}
}
class test {
id: number
name: string
constructor(id: number, name: string) {
this.id = id
this.name = name
}
}
更多关于HarmonyOS 鸿蒙Next中属性的值变化如何刷新UI的实战教程也可以访问 https://www.itying.com/category-93-b0.html
方式一:
使用@State,但这这个只能观察一层对象UI变化,如果使用this.list[0].name = ‘刘小宇’,UI不会刷新。
this.list[0] = new test(this.list[0].id, ‘刘小宇’)这样就可以刷新。
@Entry
@Component
struct MoreViewPage {
[@State](/user/State) list: test[] = [new test(0, '壹'), new test(1, '贰')]
build() {
Column() {
ForEach(this.list, (item: test) => {
Row() {
Text(`${item.id}---${item.name}`)
}
})
Text('点击').fontSize(20).onClick(() => {
this.list[0].name = '刘小宇'
this.list[0] = new test(this.list[0].id, '刘小宇')
})
}
}
}
class test {
id: number
name: string
constructor(id: number, name: string) {
this.id = id
this.name = name
}
}
方式二:使用@Observed,需要将Foreach里面的item需要封装成Component,然后才能触发UI刷新。参考官网里面Demo:对象数组
其他方式,可以使用@LocalStorage、@AppStorage也可以实现,但是相对复杂麻烦一下,不推荐
更多关于HarmonyOS 鸿蒙Next中属性的值变化如何刷新UI的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
好的好的~谢谢~,
在HarmonyOS中,UI的刷新通常通过数据绑定机制来实现。当属性的值发生变化时,系统会自动检测到这些变化并更新相应的UI组件。具体来说,HarmonyOS提供了@State
、@Link
、@Prop
等装饰器来管理组件状态的变化。
-
@State
装饰器:用于管理组件内部的状态。当使用@State
修饰的属性发生变化时,与之绑定的UI组件会自动刷新。 -
@Link
装饰器:用于在父子组件之间共享状态。当父组件的状态发生变化时,子组件中通过@Link
绑定的UI也会自动更新。 -
@Prop
装饰器:用于从父组件传递数据到子组件。当父组件的属性值发生变化时,子组件中通过@Prop
绑定的UI也会更新。
此外,HarmonyOS还提供了@Watch
装饰器,用于监听特定属性的变化,并在变化时执行指定的回调函数,从而实现更复杂的UI更新逻辑。
通过上述机制,HarmonyOS能够高效地管理UI的刷新,确保当属性值变化时,UI能够及时更新。