ArkTS不支持动态更改对象的布局,因此不支持全局作用域和globalThis。替换方案参考如下:
- 通过一个单例的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;
}
}
- 使用:
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%')
}
}