HarmonyOS 可以通过其他类中的静态属性,更新本类中的UI吗?

class A{ 
static  num:number = 0 
} 
struct B{ 
build(){ 
} 
}

如何在B中根据A类中的num更新UI?


HarmonyOS
2024-11-04 11:58:17
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Heiang

​被状态装饰器装饰的变量,状态变量值的改变会引起UI的渲染更新。示例:@State num: number = 1,其中,@State是状态装饰器,num是状态变量。可以将示例写成:@State num: number = A.num;当后续num改变时就会触发ui刷新。状态管理参考链接:​https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-state-management-overview-V5

请尝试将定时器方法代码写在aboutToAppear() :​

export class DataStore { 
  public currInterval: number = 0; 
  private static instance: DataStore; 
  @Track public test: number =  
  public static getInstance(): DataStore { 
    if (!DataStore.instance) { 
      DataStore.instance = new DataStore(); 
    } 
    return DataStore.instance; 
  } 
  public getRandomVal(): number { 
    const min = 1; 
    const max = 100; 
    const randomInt = Math.floor(Math.random() * (max - min + 1)) + min; 
    return randomInt 
  } 
  public startTime() { 
    this.currInterval = setInterval(() => { 
      this.test = this.getRandomVal() 
    }, 1000) 
  } 
} 
@Entry({ routeName: 'SwiperDemo' }) 
@Component 
export struct SwiperDemo { 
  dataSource: DataStore = DataStore.getInstance() 
  @State test: number = DataStore.getInstance().test 
  @State currInterval: number = 0; 
  aboutToAppear() { 
    // DataStore.getInstance().startTime() 
    this.currInterval = setInterval(() => { 
      this.test = this.dataSource.getRandomVal() 
    }, 1000) 
  } 
  aboutToDisappear() { 
    clearTimeout(this.currInterval); 
  } 
  build() { 
    Text(this.test.toString()).fontSize(30).padding({ top: 50 }) 
      .onClick(() => { 
        this.test = DataStore.getInstance().getRandomVal() 
        console.log('tj startTime') 
      }) 
  } 
}

​AppStorage是应用全局的UI状态存储。参考链接:​https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-appstorage-V5

分享
微博
QQ
微信
回复
2024-11-04 17:04:31
相关问题
HarmonyOS UI组件提供setAlpha属性
41浏览 • 1回复 待解决
HarmonyOS 属性默认值问题
262浏览 • 1回复 待解决
native侧如何使用静态方法
837浏览 • 1回复 待解决
native侧如何调用静态方法?
1132浏览 • 1回复 待解决
HarmonyOS 开发需要工具
249浏览 • 1回复 待解决
HarmonyOS UI组件是什么?
347浏览 • 1回复 待解决