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

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

HarmonyOS
2024-03-17 13:53:27
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
depengli

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; 
  } 
}

2. 使用:

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

参考链接

适配指导案例

分享
微博
QQ
微信
回复
2024-03-18 16:47:53
相关问题
JS的input值文本对齐如何实现?
6453浏览 • 1回复 待解决
ArkTS 可以使用 console 打印日志吗?
940浏览 • 1回复 待解决
请问ArkTSthis使用场景是什么?
167浏览 • 1回复 待解决
Image无法使用bindContextMenu
158浏览 • 1回复 待解决
求大佬告知arkts如何获取oaid
69浏览 • 1回复 待解决
ArkTs如何获取对象的类名
60浏览 • 1回复 待解决
arkTS无法创建子窗口有了解的吗?
866浏览 • 0回复 待解决
Image怎么替换svg图片?
6425浏览 • 1回复 待解决
ArkTS可以使用Toast吗?
1782浏览 • 1回复 待解决
DevEco Device无法使用Previewer预览
29322浏览 • 3回复 待解决