HarmonyOS 鸿蒙Next ArkTS语言教程入门学习第25天,@Watch装饰器:状态变量更改通知。
HarmonyOS 鸿蒙Next ArkTS语言教程入门学习第25天,@Watch装饰器:状态变量更改通知。
1、$$语法:内置组件双向同步
$$运算符为系统内置组件提供TS变量的引用,使得TS变量和系统内置组件的内部状态保持同步。
内部状态具体指什么取决于组件。例如,Refresh组件的refreshing参数。
2、使用规则
3、使用示例
以Refresh组件的refreshing参数为例:
当使用了$$符号绑定isRefreshing状态变量时,页面进行下拉操作,isRefreshing会变成true。
同时,Text中的isRefreshing状态也会同步改变为true,如果不使用$$符号绑定,则不会同步改变。
// xxx.ets
@Entry
@Component
struct RefreshExample {
[@State](/user/State) isRefreshing: boolean = false
[@State](/user/State) counter: number = 0
build() {
Column() {
Text('Pull Down and isRefreshing: ' + this.isRefreshing)
.fontSize(30)
.margin(10)
Refresh({ refreshing: $$this.isRefreshing, offset: 120, friction: 100 }) {
Text('Pull Down and refresh: ' + this.counter)
.fontSize(30)
.margin(10)
}
.onStateChange((refreshStatus: RefreshStatus) => {
console.info('Refresh onStateChange state is ' + refreshStatus)
})
}
}
}
更多关于HarmonyOS 鸿蒙Next ArkTS语言教程入门学习第25天,@Watch装饰器:状态变量更改通知。的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
ArkTS语言中的@Watch装饰器用于监听状态变量的变化,当被装饰的状态变量发生改变时,会自动触发指定的回调函数。@Watch装饰器可以帮助开发者更方便地响应状态变化,执行相应的逻辑。
@Watch装饰器的基本语法如下:
[@Watch](/user/Watch)(callback: (newValue: T, oldValue: T) => void)
stateVariable: T;
其中,callback
是一个回调函数,它会在stateVariable
的值发生变化时被调用。回调函数接收两个参数:newValue
表示状态变量的新值,oldValue
表示状态变量的旧值。
示例代码:
@Entry
@Component
struct MyComponent {
@State [@Watch](/user/Watch)((newValue: number, oldValue: number) => {
console.log(`Value changed from ${oldValue} to ${newValue}`);
}) count: number = 0;
build() {
Column() {
Button('Increment')
.onClick(() => {
this.count += 1;
})
Text(`Count: ${this.count}`)
}
}
}
在这个示例中,count
是一个被[@Watch](/user/Watch)
装饰的状态变量。每当count
的值发生变化时,回调函数会打印出新旧值。
@Watch装饰器适用于需要监听状态变量变化并执行特定操作的场景,例如更新UI、触发网络请求等。通过使用@Watch装饰器,开发者可以更简洁地管理状态变化带来的副作用,而不需要手动编写额外的逻辑来处理状态更新。
更多关于HarmonyOS 鸿蒙Next ArkTS语言教程入门学习第25天,@Watch装饰器:状态变量更改通知。的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在第25天的HarmonyOS鸿蒙Next ArkTS语言教程中,我们学习了@Watch
装饰器的使用。@Watch
用于监听状态变量的变化,当被监听的状态变量发生改变时,会自动触发指定的回调函数。通过@Watch
,开发者可以更灵活地响应状态变化,实现数据与UI的同步更新。使用示例:
@State count: number = 0;
@Watch('count')
onCountChanged(newValue: number, oldValue: number) {
console.log(\`Count changed from \${oldValue} to \${newValue}\`);
}
当count
发生变化时,onCountChanged
方法会被自动调用,方便开发者进行相关逻辑处理。