@react-native-ohos/react-native-orientation
v3.2.1
Published
Listen to device orientation changes in React Native applications and programmatically set preferred orientations on a per screen basis
Readme
文档模板:v0.4.2
本项目基于 react-native-orientation 开发。
该第三方库的仓库已迁移至 Gitcode,且支持直接从 npm 下载,新的包名为:@react-native-ohos/react-native-orientation(JS 别名 react-native-orientation),版本所属关系如下:
| 三方库名称 | 三方库版本(npm地址) | 发布信息 | 支持RN版本 | Autolink | 编译API版本 | 社区基线版本 | 源码地址 | | - | - | - | - | - | - | - | - | | @react-native-ohos/react-native-orientation | ~ 3.2.0 | Gitcode Releases | 0.77.* | 否 | API12+ | 3.1.3 | br_rnoh0.77 |
简介
react-native-orientation 用于在 React Native 应用中监听设备方向变化,并支持以编程方式锁定/解锁屏幕方向(竖屏、横屏、左旋横屏、右旋横屏)。
本库为其提供 React Native 鸿蒙(HarmonyOS)适配,基于 TurboModule 实现,支持方向监听、方向获取、方向锁定等全部接口。
下载安装
进入到工程目录并输入以下命令:
npm
npm install @react-native-ohos/react-native-orientationyarn
yarn add @react-native-ohos/react-native-orientationLink
| | 是否支持autolink | RN框架版本 | | - | - | - | | ~3.2.0 | 否 | 0.77.* |
使用AutoLink的工程需要根据该文档配置,Autolink框架指导文档:https://gitcode.com/CPF-RN/ohos_react_native/blob/master/docs/zh-cn/Autolinking.md
如您使用的版本支持 Autolink,并且工程已接入 Autolink,可跳过ManualLink配置。
首先需要使用 DevEco Studio 打开项目里的 HarmonyOS 工程 harmony。
1. Overrides RN SDK
为了让工程依赖同一个版本的 RN SDK,需要在工程根目录的 oh-package.json5 添加 overrides 字段,指向工程需要使用的 RN SDK 版本。替换的版本既可以是一个具体的版本号,也可以是一个模糊版本,还可以是本地存在的 HAR 包或源码目录。
关于该字段的作用请阅读官方说明
{
...
"overrides": {
"@rnoh/react-native-openharmony" : "^0.77.73"
}
}2. 引入原生端代码
目前有两种方法:
- 通过 har 包引入(在 IDE 完善相关功能后该方法会被遗弃,目前首选此方法);
- 直接链接源码。
方法一:通过 har 包引入(推荐)
[!TIP] har 包位于三方库安装路径的
harmony文件夹下。
打开 entry/oh-package.json5,添加以下依赖
"dependencies": {
"@rnoh/react-native-openharmony": "file:../react_native_openharmony",
"@react-native-ohos/react-native-orientation": "file:../../node_modules/@react-native-ohos/react-native-orientation/harmony/rn_orientation.har"
}点击右上角的 sync 按钮
或者在终端执行:
cd entry
ohpm install方法二:直接链接源码
[!TIP] 如需使用直接链接源码,请参考直接链接源码说明
3. 配置 CMakeLists 和引入 RNOrientationPackage
若工程已接入 RNOH AutoLink,且本库的
harmony.autolinking配置生效,则 CMake 与PackageProvider注册可由 AutoLink 自动生成,可跳过本节手动配置。
打开 entry/src/main/cpp/CMakeLists.txt,添加:
project(rnapp)
cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_SKIP_BUILD_RPATH TRUE)
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(NODE_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../node_modules")
+ set(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../react-native-harmony/harmony/cpp")
set(LOG_VERBOSITY_LEVEL 1)
set(CMAKE_ASM_FLAGS "-Wno-error=unused-command-line-argument -Qunused-arguments")
set(CMAKE_CXX_FLAGS "-fstack-protector-strong -Wl,-z,relro,-z,now,-z,noexecstack -s -fPIE -pie")
set(WITH_HITRACE_SYSTRACE 1) # for other CMakeLists.txt files to use
add_compile_definitions(WITH_HITRACE_SYSTRACE)
add_subdirectory("${RNOH_CPP_DIR}" ./rn)
# RNOH_BEGIN: manual_package_linking_1
add_subdirectory("../../../../sample_package/src/main/cpp" ./sample-package)
+ add_subdirectory("${OH_MODULES}/@react-native-ohos/react-native-orientation/src/main/cpp" ./rn_orientation)
# RNOH_END: manual_package_linking_1
file(GLOB GENERATED_CPP_FILES "./generated/*.cpp")
add_library(rnoh_app SHARED
${GENERATED_CPP_FILES}
"./PackageProvider.cpp"
"${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp"
)
target_link_libraries(rnoh_app PUBLIC rnoh)
# RNOH_BEGIN: manual_package_linking_2
target_link_libraries(rnoh_app PUBLIC rnoh_sample_package)
+ target_link_libraries(rnoh_app PUBLIC rnoh_orientation)
# RNOH_END: manual_package_linking_2打开 entry/src/main/cpp/PackageProvider.cpp,添加:
#include "RNOH/PackageProvider.h"
#include "SamplePackage.h"
+ #include "RNOritentionPackage.h"
using namespace rnoh;
std::vector<std::shared_ptr<Package>> PackageProvider::getPackages(Package::Context ctx) {
return {
std::make_shared<SamplePackage>(ctx),
+ std::make_shared<RNOritentionPackage>(ctx),
};
}4. 在 ArkTs 侧引入 RNOrientationPackage
打开 entry/src/main/ets/RNPackagesFactory.ts,或者 entry/src/main/ets/rn/RNPackagesFactory.ts,添加:
...
+ import { RNOrientationPackage } from '@react-native-ohos/react-native-orientation/ts';
export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
return [
new SamplePackage(ctx),
+ new RNOrientationPackage(ctx),
];
}5. 运行
点击右上角的 sync 按钮
或者在终端执行:
cd entry
ohpm install然后编译、运行即可。
约束与限制
兼容性
要使用此库,需要使用正确的 React-Native 和 RNOH 版本。另外,还需要使用配套的 DevEco Studio 和手机 ROM。
本文档内容基于以下版本验证通过:
- RNOH: 0.77.18; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.858; ROM: 6.0.0.112;
权限要求
无特殊权限要求。
编译运行API要求
[!TIP] 当前三方库所有版本均已实现版本隔离,支持在
API12+工程编译,及API12+ROM运行。
使用示例
下面的代码展示了这个库的基本使用场景:
[!WARNING] 使用时 import 的库名不变,JS 侧通过
react-native-orientation导入。
import React, { useEffect, useState } from 'react';
import { Alert, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import Orientation from 'react-native-orientation';
export default function OrientationDemo() {
const [orientation, setOrientation] = useState<string>();
useEffect(() => {
// 开启方向变化监听
Orientation.addOrientationListener((o) => setOrientation(o));
return () => {
// 退出时移除监听
Orientation.removeOrientationListener((o) => setOrientation(o));
};
}, []);
return (
<View style={styles.container}>
<Text>{`Current Orientation: ${orientation}`}</Text>
<TouchableOpacity
onPress={() => Orientation.getOrientation((err, o) => Alert.alert(`当前方向: ${o}`))}
style={styles.button}>
<Text style={styles.instructions}>获取当前屏幕方向</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => Orientation.lockToPortrait()} style={styles.button}>
<Text style={styles.instructions}>锁定竖屏</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => Orientation.lockToLandscape()} style={styles.button}>
<Text style={styles.instructions}>锁定横屏</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => Orientation.unlockAllOrientations()} style={styles.button}>
<Text style={styles.instructions}>解锁旋转锁定</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, alignItems: 'center', backgroundColor: '#F5FCFF', marginTop: 20 },
instructions: { textAlign: 'center', color: '#eeeeee' },
button: {
padding: 5, margin: 5, borderWidth: 1, borderColor: 'white',
borderRadius: 3, backgroundColor: 'grey',
},
});使用说明
监听方向变化
import Orientation from 'react-native-orientation';
const cb = (orientation) => console.log(orientation);
Orientation.addOrientationListener(cb);
Orientation.removeOrientationListener(cb);
const cb2 = (specificOrientation) => console.log(specificOrientation);
Orientation.addSpecificOrientationListener(cb2);
Orientation.removeSpecificOrientationListener(cb2);锁定 / 解锁方向
Orientation.lockToPortrait(); // 锁定竖屏
Orientation.lockToLandscape(); // 锁定横屏(正反横屏,受控制中心旋转开关控制)
Orientation.lockToLandscapeLeft(); // 锁定左旋横屏
Orientation.lockToLandscapeRight(); // 锁定右旋横屏
Orientation.unlockAllOrientations(); // 解锁,允许自由旋转获取当前方向
// 回调形式,err 为错误信息(成功时为 undefined)
Orientation.getOrientation((err, orientation) => {
console.log(orientation); // 'PORTRAIT' / 'LANDSCAPE' / ...
});
Orientation.getSpecificOrientation((err, specificOrientation) => {
console.log(specificOrientation); // 'PORTRAIT' / 'LANDSCAPE-LEFT' / ...
});
// 同步获取应用启动时的初始方向
const initial = Orientation.getInitialOrientation();接口说明
[!TIP] "Platform"列表示该属性在原三方库上支持的平台。
[!TIP] "HarmonyOS Support"列为 yes 表示 HarmonyOS 平台支持该属性;no 则表示不支持;partially 表示部分支持。使用方法跨平台一致,效果对标 iOS 或 Android 的效果。
本库对外暴露 Orientation 模块(TurboModule ReactNativeOrientation 的 JS 封装),方法、事件及关联说明如下。
方法
| Name | Description | Type | Platform | HarmonyOS Support |
| - | - | - | - | - |
| lockToPortrait | 锁定应用程序的方向为纵向(竖屏) | () => void | iOS / Android | yes |
| lockToLandscape | 锁定应用程序的方向为横向(横屏,正反横屏均允许,受控制中心旋转开关控制) | () => void | iOS / Android | yes |
| lockToLandscapeLeft | 锁定应用程序的方向为横向,并向左旋转 | () => void | iOS / Android | yes |
| lockToLandscapeRight | 锁定应用程序的方向为横向,并向右旋转 | () => void | iOS / Android | yes |
| unlockAllOrientations | 解锁应用程序的方向,允许设备自由旋转 | () => void | iOS / Android | yes |
| getOrientation | 获取当前设备的方向 | (cb: (err: string, orientation: string) => void) => void | iOS / Android | yes |
| getSpecificOrientation | 获取当前设备的具体方向(区分左旋/右旋) | (cb: (err: string, orientation: string) => void) => void | iOS / Android | yes |
事件
| Name | Description | Type | Platform | HarmonyOS Support |
| - | - | - | - | - |
| addOrientationListener | 开启监听屏幕方向变化事件 | (cb: (orientation: string) => void) => void | iOS / Android | yes |
| addSpecificOrientationListener | 开启监听屏幕具体方向变化事件 | (cb: (specificOrientation: string) => void) => void | iOS / Android | yes |
| removeOrientationListener | 移除监听屏幕方向变化事件 | (cb: (orientation: string) => void) => void | iOS / Android | yes |
| removeSpecificOrientationListener | 移除监听屏幕具体方向变化事件 | (cb: (specificOrientation: string) => void) => void | iOS / Android | yes |
遗留问题
无
其他
无
目录结构
/rntpc_react-native-orientation # 项目根目录
├── harmony # 鸿蒙适配代码
│ └─ rn_orientation.har # har 包
│ └─ rn_orientation # 鸿蒙适配核心代码
│ └─ Index.ets # 鸿蒙适配代码入口
│ └─ ts.ts # ArkTS 侧类型导出入口
│ └─ src/main
│ └─ ets
│ └─ RNOritentionPackage.ts # 鸿蒙侧 Package(TurboModule 注册枢纽)
│ └─ RNOritentionTurboModule.ts # TurboModule 实现
│ └─ Logger.ts # 日志
│ └─ generated/ # codegen 生成的 ArkTS 代码
│ └─ cpp
│ └─ CMakeLists.txt # C++ 侧构建配置(目标 rnoh_orientation)
│ └─ RNOrientationPackage.h # C++ Package
├── src # RN 侧 Spec
│ └─ NativeReactNativeOrientation.ts # TurboModule Spec 定义(codegen 输入)
├── index.js # JS 入口(TurboModule 封装 + 事件监听)
├── README.md # 中文文档
├── README_en.md # 英文文档贡献代码
使用过程中发现任何问题都可以提交 Issue,当然,也非常欢迎提交 PR 。
开源协议
本项目基于 ISC License ,请自由地享受和参与开源。
