ArkTS中globalThis无法使用该如何替换?

ArkTS中globalThis无法使用该如何替换

阅读 1.1k
1 个回答

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%') 
  } 
}

参考链接

适配指导案例

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进