如何在自定义组件的构建流程里跟踪组件数据或者状态,如在build里增加日志跟踪状态变量等

如何在自定义组件的构建流程里跟踪组件数据或者状态,如在build里增加日志跟踪状态变量等

HarmonyOS
2024-03-17 15:08:30
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
e_lion

使用@Watch回调来监测状态变量的变化,如果执行回调函数,说明在下一次vysnc信号发送时,使用该状态变量的UI会刷新绘制。

参考代码如下:

@Component 
struct TotalView { 
  @Prop @Watch('onCountUpdated') count: number = 0; 
  @State total: number = 0; 
  // @Watch 回调 
  onCountUpdated(propName: string): void { 
    this.total += this.count; 
  } 
 
  build() { 
    Text(`Total: ${this.total}`) 
  } 
} 
 
@Entry 
@Component 
struct CountModifier { 
  @State count: number = 0; 
 
  build() { 
    Column() { 
      Button('add to basket') 
        .onClick(() => { 
          this.count++ 
        }) 
      TotalView({ count: this.count }) 
    } 
  } 
}

参考链接

watch和自定义组件更新

分享
微博
QQ
微信
回复
2024-03-18 20:49:27
提问
该提问已有0人参与 ,帮助了0人