HarmonyOS鸿蒙Next中@Watch监听问题
HarmonyOS鸿蒙Next中@Watch监听问题
在自定义组件中配置@Watch
@Component
export default struct Test {
@State [@Watch](/user/Watch)('onCount') count: number = 0;
onCount():void {
setTimeout(() => {
this.count += 1;
}, 1000)
}
}
在这样配置就报Cannot find name ‘onWatch’ in struct ‘Test’.错误
更多关于HarmonyOS鸿蒙Next中@Watch监听问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html
@Component struct Son_1 { @State @Watch(‘onCount’) count: number = 0; aboutToAppear(): void { this.onCount(); } onCount():void { setTimeout(() => { this.count += 1; }, 1000) } build() { Column(){ Row(){ Text(‘Count:’) Text(this.count + “”) } }.width(“100%”).height(“100%”) } }
@Entry @Component struct Index {
build() { RelativeContainer() { Son_1() } .height(‘100%’) .width(‘100%’) } }
可以参考上面的代码,看一下是否能解决你的问题。
更多关于HarmonyOS鸿蒙Next中@Watch监听问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
我跑你的代码是没问题的
@Entry
@Component
export default struct Page6 {
@State @Watch('onCount') count: number = 0;
aboutToAppear(): void {
this.onCount()
}
build() {
Column(){
Text(this.count+"")
}.width("100%").height("100%")
}
onCount():void {
setTimeout(() => {
this.count += 1;
}, 1000)
}
}
因为您的组件使用是@Entry主入口,我用的是自定义组件呢,
一样的,自定义也能用,没啥问题,
在HarmonyOS Next中,@Watch
装饰器用于监听状态变量的变化。当被@Watch
修饰的状态变量改变时,装饰器绑定的回调函数会被触发。使用方法是在状态变量声明后添加@Watch
回调函数。例如:
@State @Watch('onCountChange') count: number = 0;
onCountChange() {
console.log('count changed');
}
注意:@Watch
的回调函数会在状态变化后执行,且会携带新旧值参数。多个状态变量可以共用同一个回调函数。装饰器只能同步执行,不能用于异步操作。
在HarmonyOS Next中,@Watch装饰器的使用方式需要调整。您遇到的错误是因为@Watch装饰器的回调函数命名与调用不匹配。正确的写法应该是:
@Component
export default struct Test {
@State [@Watch](/user/Watch)('onCountChange') count: number = 0;
onCountChange(): void {
setTimeout(() => {
this.count += 1;
}, 1000)
}
}
关键点:
- @Watch装饰器中指定的回调函数名(如’onCountChange’)必须与组件中定义的方法名完全一致
- 回调函数会在被监视的变量(count)变化时自动触发
- 注意避免在回调函数中直接修改被监视的变量,否则可能导致无限循环
您示例中的错误是因为@Watch(‘onCount’)指定了’onCount’作为回调函数,但实际定义的方法是’onCountChange’,导致找不到对应方法。