鸿蒙5.0开发【ArkTS中globalThis无法使用该如何替换】应用运维

ArkTS不支持动态更改对象的布局,因此不支持全局作用域和globalThis。替换方案参考如下:

  1. 通过一个单例的map来做中转:
import { common } from '@kit.AbilityKit'; 
 
// 构造单例对象 
export class GlobalThis { 
  private constructor() {}; 
  private static instance: GlobalThis; 
  private _uiContexts = new Map<string, common.UIAbilityContext>(); 
  private value = ''; 
 
  public static getInstance(): GlobalThis { 
    if (!GlobalThis.instance) { 
      GlobalThis.instance = new GlobalThis(); 
    } 
    return GlobalThis.instance; 
  } 
 
  getContext(key: string): common.UIAbilityContext | undefined { 
    return this._uiContexts.get(key); 
  } 
 
  setContext(key: string, value: common.UIAbilityContext): void { 
    this._uiContexts.set(key, value); 
  } 
 
  setValue(value:string){ 
    this.value = value 
  } 
 
  getValue():string{ 
    return this.value; 
  } 
}
  1. 使用:
import { GlobalThis } from '../utils/globalThis'; 
 
@Entry 
@Component 
struct Index { 
  @State value: string = GlobalThis.getInstance().getValue(); 
 
  build() { 
    Row() { 
      Column() { 
        Text(this.value) 
          .fontSize(50) 
          .fontWeight(FontWeight.Bold) 
        Button("setValue") 
          .fontSize(50) 
          .fontWeight(FontWeight.Bold) 
          .onClick(() => { 
            GlobalThis.getInstance().setValue("TEST"); 
          }) 
        Button("getValue") 
          .fontSize(50) 
          .fontWeight(FontWeight.Bold) 
          .onClick(() => { 
            this.value = GlobalThis.getInstance().getValue(); 
          }) 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值