import {
  RNApp,
  RNOHErrorDialog,
  RNOHLogger,
  RNOHCoreContext,
  RNInstance,
  ResourceJSBundleProvider
} from '@rnoh/react-native-openharmony';
import { RNInstanceManager } from "../rn/RNInstanceManager";
import { buildCustomRNComponent } from "../rn/CustomRNComponent";

const wrappedCustomRNComponentBuilder = wrapBuilder(buildCustomRNComponent);

@Entry
@Component
struct Flight {
  @StorageLink('RNOHCoreContext') private rnohCoreContext: RNOHCoreContext | undefined = undefined;
  @State shouldShow: boolean = false;
  private logger!: RNOHLogger;
  private rnInstance: RNInstance | undefined;

  async aboutToAppear() {
    this.logger = this.rnohCoreContext!.logger.clone("Flight");
    const stopTracing = this.logger.clone("aboutToAppear").startTracing();
    this.rnInstance = await RNInstanceManager.getInstance("Flight");
    this.shouldShow = true;
    stopTracing();
  }

  onBackPress(): boolean | undefined {
    this.rnohCoreContext!.dispatchBackPress();
    return true;
  }

  build() {
    Column() {
      if (this.rnohCoreContext && this.shouldShow) {
        if (this.rnohCoreContext?.isDebugModeEnabled) {
          RNOHErrorDialog({ ctx: this.rnohCoreContext });
        }
        RNApp({
          rnInstanceConfig: {
            rnInstance: this.rnInstance as RNInstance,
          },
          initialProps: { "foo": "bar" } as Record<string, string>,
          appKey: "flight",
          wrappedCustomRNComponentBuilder: wrappedCustomRNComponentBuilder,
          onSetUp: (rnInstance) => {
            rnInstance.enableFeatureFlag("ENABLE_RN_INSTANCE_CLEAN_UP");
          },
          jsBundleProvider: new ResourceJSBundleProvider(
            this.rnohCoreContext.uiAbilityContext.resourceManager, 'bundle/cp/flight.harmony.bundle')
        })
      }
    }
    .height('100%')
    .width('100%')
  }
}

这是一个基于 OpenHarmony ArkUI 框架开发的航班页面组件,采用了声明式 UI 开发范式,集成了 React Native 混合开发能力。让我为您详细解析这个组件的完整架构和实现原理。

组件架构概述

这是一个完整的鸿蒙应用页面组件,采用 @Entry 装饰器标识为页面入口,@Component 装饰器定义自定义组件。该组件展现了 OpenHarmony 与 React Native 混合开发的先进架构模式。

核心依赖解析

1. React Native for OpenHarmony 核心模块

import {
  RNApp,
  RNOHErrorDialog,
  RNOHLogger,
  RNOHCoreContext,
  RNInstance,
  ResourceJSBundleProvider
} from '@rnoh/react-native-openharmony';
  • RNApp‌:React Native 应用容器组件,负责渲染和管理 React Native 内容
  • RNOHErrorDialog‌:错误对话框组件,在调试模式下显示运行时错误
  • RNOHLogger‌:日志记录器,提供分级日志和性能追踪功能
  • RNOHCoreContext‌:React Native 核心上下文,包含应用状态、UIAbility 上下文等关键信息

2. 本地模块导入

import { RNInstanceManager } from "../rn/RNInstanceManager";
import { buildCustomRNComponent } from "../rn/CustomRNComponent";

组件生命周期管理

1. 装饰器系统

  • @Entry‌:标识该组件为页面级入口,系统会为其创建独立的页面栈
  • @Component‌:定义自定义组件结构,将数据与 UI 绑定

2. 状态管理机制

@StorageLink('RNOHCoreContext') private rnohCoreContext: RNOHCoreContext | undefined = undefined;
@State shouldShow: boolean = false;
  • @StorageLink‌:与 AppStorage 中的状态建立双向绑定,用于共享全局状态
  • @State‌:组件内部状态,变化时会触发 UI 重新渲染

核心方法深度解析

1. aboutToAppear() 生命周期方法

async aboutToAppear() {
  this.logger = this.rnohCoreContext!.logger.clone("Flight");
  const stopTracing = this.logger.clone("aboutToAppear").startTracing();
  this.rnInstance = await RNInstanceManager.getInstance("Flight");
  this.shouldShow = true;
  stopTracing();
}

执行流程‌:

  • 日志器初始化‌:从核心上下文中克隆专门的日志器实例
  • 性能追踪‌:使用 startTracing() 和 stopTracing() 包装关键操作
  • RN实例获取‌:异步获取预注册的 React Native 实例
  • 显示状态更新‌:设置组件为可显示状态

2. onBackPress() 物理返回键处理

onBackPress(): boolean | undefined {
  this.rnohCoreContext!.dispatchBackPress();
  return true;
}

返回机制‌:

  • 拦截系统返回键事件
  • 转发给 React Native 上下文处理
  • 返回 true 表示已消费该事件,阻止默认行为

UI 构建系统详解

1. 条件渲染架构

if (this.rnohCoreContext && this.shouldShow) {
  if (this.rnohCoreContext?.isDebugModeEnabled) {
    RNOHErrorDialog({ ctx: this.rnohCoreContext });
  }
  // RNApp 组件渲染
}

渲染逻辑‌:

  • 上下文存在性检查
  • 组件显示状态验证
  • 调试模式错误对话框显示

2. RNApp 组件配置

RNApp({
  rnInstanceConfig: {
    rnInstance: this.rnInstance as RNInstance,
  },
  initialProps: { "foo": "bar" } as Record<string, string>,
  appKey: "flight",
  wrappedCustomRNComponentBuilder: wrappedCustomRNComponentBuilder,
  onSetUp: (rnInstance) => {
    rnInstance.enableFeatureFlag("ENABLE_RN_INSTANCE_CLEAN_UP");
  },
  jsBundleProvider: new ResourceJSBundleProvider(
    this.rnohCoreContext.uiAbilityContext.resourceManager, 'bundle/cp/flight.harmony.bundle')
})

配置参数解析‌:

  • rnInstanceConfig‌:React Native 实例配置
  • initialProps‌:初始化属性,可传递任意数据给 RN 组件
  • appKey‌:与 RN 工程中注册的组件名称必须一致
  • wrappedCustomRNComponentBuilder‌:自定义 RN 组件构建器
  • onSetUp‌:实例设置完成后的回调函数
  • jsBundleProvider‌:JavaScript Bundle 提供器

错误处理与调试机制

1. 调试模式支持

if (this.rnohCoreContext?.isDebugModeEnabled) {
  RNOHErrorDialog({ ctx: this.rnohCoreContext });
}

RNOHErrorDialog‌ 组件:

  • 仅在调试模式下显示
  • 捕获和展示运行时错误
  • 提供友好的错误信息界面
  • 性能优化策略

1. 异步加载机制

使用 async/await 异步获取 RN 实例,避免阻塞 UI 线程。

2. 条件渲染优化

通过 shouldShow 状态控制组件显示,确保在资源准备完成前不进行渲染。

建议‌:在实际开发中,建议为每个业务模块配置独立的 Bundle 文件,这样可以实现更精细化的资源管理和按需加载优化。


在这里插入图片描述


接下来通过打包命令npn run harmony将reactNative的代码打包成为bundle,这样可以进行在开源鸿蒙OpenHarmony中进行使用。

在这里插入图片描述
最终实现效果是:

请添加图片描述

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐