鸿蒙HarmonyOS (React Native)的实战教程

发布于:2025-06-02 ⋅ 阅读:(25) ⋅ 点赞:(0)

一、环境配置

  1. 安装鸿蒙专属模板

    bashCopy Code

    npx react-native@0.72.5 init HarmonyApp --template react-native-template-harmony:ml-citation{ref="4,6" data="citationList"}

  2. 配置 ArkTS 模块路径
    在 entry/src/main/ets 目录下创建原生模块(下文示例)


二、实战:RN 调用鸿蒙传感器(ArkTS 原生模块)

1. 创建鸿蒙原生模块 SensorManager.ets

typescriptCopy Code

// entry/src/main/ets/sensors/SensorManager.ets import sensor from '@ohos.sensor'; export class SensorManager { // 暴露给 RN 的加速度计监听方法 static startAccelerometer(callback: (data: object) => void): void { sensor.on(sensor.SensorId.ACCELEROMETER, (data) => { callback({ x: data.x, y: data.y, z: data.z }); }); } }

2. RN 侧调用传感器(JS 代码)

javascriptCopy Code

// App.js import { NativeModules } from 'react-native'; const { SensorManager } = NativeModules; // 启动加速度监听 useEffect(() => { SensorManager.startAccelerometer(data => { console.log("加速度数据:", data.x, data.y, data.z); }); }, []);

3. 权限声明(关键步骤)

在 module.json5 中添加:

jsonCopy Code

{ "module": { "requestPermissions": [ { "name": "ohos.permission.ACCELEROMETER" } ] } }

‌:传感器需真机测试,模拟器无数据返回


三、鸿蒙 UI 组件封装(ArkTS + RN)

1. 创建鸿蒙原生组件 HarmonyButton.ets

typescriptCopy Code

// entry/src/main/ets/components/HarmonyButton.ets @Component export struct HarmonyButton { @State label: string = "Click Me" onClick: () => void = () => {} build() { Button(this.label) .width(150) .height(50) .onClick(() => this.onClick()) } }

2. 桥接到 React Native

javascriptCopy Code

// harmony-bridge.js import { requireNativeComponent } from 'react-native'; export default requireNativeComponent('HarmonyButton');

3. RN 中使用该组件

jsxCopy Code

// App.js import HarmonyButton from './harmony-bridge'; <HarmonyButton label="鸿蒙按钮" style={{ width: 150, height: 50 }} onClick={() => alert('ArkTS 按钮被点击!')} />


四、调试技巧

  1. 日志查看
  2. bashCopy Code

  3. hdc shell hilog | grep "ReactNativeJS" # 过滤 RN 日志

  4. 性能分析
    • 使用 DevEco Profiler 监控 JS 线程负载(优化后渲染延迟降低 40%)

五、避坑指南

问题 解决方案
RN 无法加载鸿蒙组件 检查 harmony/components 路径无中文命名
传感器返回 null 真机需开启开发者模式的「传感器调试权限」
热更新失效 关闭 DevEco Studio 的 ArkCompiler 优化模式

网站公告

今日签到

点亮在社区的每一天
去签到