HarmonyOS 鸿蒙Next ArkTS中globalThis无法使用该如何替换
HarmonyOS 鸿蒙Next 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; } }
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%’) } }
参考链接
更多关于HarmonyOS 鸿蒙Next ArkTS中globalThis无法使用该如何替换的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
大佬 你这种方式可以存储多个值吗?
import common from ‘@ohos.app.ability.common’;
在HarmonyOS鸿蒙Next ArkTS中,由于ArkTS不支持动态更改对象的布局,因此也不支持全局作用域和globalThis
。针对这一问题,可以通过构造单例对象来实现类似全局访问的功能。
具体替换方案如下:
- 构造单例类:创建一个包含所需全局变量的单例类,并通过私有构造函数和静态的
getInstance
方法来确保类的单例性。在这个类中,可以定义各种全局变量和方法来模拟globalThis
的功能。 - 全局变量访问:通过单例类的实例来访问和修改全局变量,而不是直接使用
globalThis
。
例如,可以创建一个名为GlobalContext
的单例类,其中包含多个全局变量和方法。在需要访问这些全局变量的地方,通过GlobalContext.getInstance()
来获取单例对象,并进而访问其内部的变量或方法。
如果问题依旧没法解决,请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html。在这里,你可以获得更专业的技术支持和帮助。