鸿蒙getContext(this)弃用后的替代方法

一、直接获取UIAbilityContext(推荐)

核心方法getUIContext().getHostContext()

特点

  • 从API 12+开始支持,是废弃getContext()后的官方替代方案
  • 返回UIAbilityContext类型对象,可直接操作Ability生命周期

示例代码

TypeScript 复制代码
import { common } from '@kit.AbilityKit';

@Entry
@Component
struct MyPage {
  // 定义上下文变量
  private context: common.UIAbilityContext = 
      this.getUIContext().getHostContext() as common.UIAbilityContext;

  build() {
    Column() {
      Button("启动Ability")
        .onClick(() => {
          // 使用上下文启动新Ability
          this.context.startAbility({ /* Want参数 */ });
        })
    }
  }
}

二、通过全局存储传递 适用场景:跨页面/非组件环境使用

TypeScript 复制代码
1、在UIAbility中存储:
// EntryAbility.ets
onWindowStageCreate(windowStage: window.WindowStage) {
  AppStorage.setOrCreate("uiContext", this.context); 
}

2、在Page中获取:
@StorageLink('uiContext') context: common.UIAbilityContext;

三、特殊场景适配

Worker线程获取

需通过可发送对象转换:

TypeScript 复制代码
import { sendableContextManager } from '@kit.AbilityKit';
const sendableCtx = sendableContextManager.convertFromContext(context);
workerPort.postMessageWithSharedSendable(sendableCtx);

API 19以下兼容方案

通过WindowStage间接获取:

TypeScript 复制代码
windowStage.getMainWindow().then(win => {
  const ctx = win.getUIContext().getHostContext();
});

⚠️ 注意事项

  1. 废弃接口 :避免使用getContext()(API 18+已废弃)
  2. 类型断言 :必须使用as common.UIAbilityContext明确类型
  3. 作用域限制 :构造函数中无法获取,需在build()或事件回调中使用
  4. 线程安全 :跨线程传递需使用sendableContextManager转换

以上方法均基于鸿蒙API 12+的ArkUI声明式范式。实际开发中优先使用第一种直接获取方式,其代码简洁且符合最新规范。

相关推荐
熊猫钓鱼>_>1 天前
【开源鸿蒙跨平台开发先锋训练营】Day 19: 开源鸿蒙React Native动效体系构建与混合开发复盘
react native·华为·开源·harmonyos·鸿蒙·openharmony
2601_949593651 天前
基础入门 React Native 鸿蒙跨平台开发:BackHandler 返回键控制
react native·react.js·harmonyos
mocoding1 天前
使用Flutter强大的图标库fl_chart优化鸿蒙版天气预报温度、降水量、湿度展示
flutter·华为·harmonyos
Cobboo1 天前
i单词上架鸿蒙应用市场之路:一次从 Android 到 HarmonyOS 的完整实战
android·华为·harmonyos
2601_949593651 天前
高级进阶 React Native 鸿蒙跨平台开发:LinearGradient 动画渐变效果
react native·react.js·harmonyos
熊猫钓鱼>_>1 天前
【开源鸿蒙跨平台开发先锋训练营】鸿蒙应用开发 Day 10 - React Native for OpenHarmony 实战:多端响应式布局与高可用交互设计
华为·开源·交互·harmonyos·鸿蒙·rn·gridrow
摘星编程1 天前
React Native鸿蒙:自定义useField字段状态绑定
react native·react.js·harmonyos
人工智能知识库1 天前
华为数通HCIA-Datacom H12-811题库(26最新详细解析)
华为·hcia-datacom·题库·h12-811·最新题库
酣大智1 天前
参考模型--数据链路层
运维·网络·网络协议·tcp/ip·华为
Miguo94well1 天前
Flutter框架跨平台鸿蒙开发——学校校历APP的开发流程
flutter·华为·harmonyos·鸿蒙