You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何将相机锁定为仅竖屏模式?

React Native 相机页面强制竖屏适配方案(Android + iOS)

一、现有方法无效的可能原因

  • react-native-orientation-locker调用时机不对,或未完成原生端配置
  • 相机组件自身的方向设置覆盖了页面/全局竖屏锁定规则
  • 导航栈的orientation配置仅作用于页面容器,无法约束原生相机组件

二、分步解决(Android + iOS通用)

1. 正确使用react-native-orientation-locker

先确认原生配置完成:

  • Android:确保AndroidManifest.xml的activity标签包含android:configChanges="orientation|screenSize|keyboardHidden"
  • iOS:自动链接后无需额外操作,手动集成需在AppDelegate.m中添加方向回调

在相机页面的生命周期内精准调用锁定/解锁逻辑:

import Orientation from 'react-native-orientation-locker';

// 函数组件示例
useEffect(() => {
  // 页面挂载后、相机启动前锁定竖屏
  Orientation.lockToPortrait();

  return () => {
    // 页面卸载时解锁,恢复全局方向设置
    Orientation.unlockAllOrientations();
  };
}, []);

2. 强制相机组件输出竖屏内容

以常用的react-native-camera为例,需在组件配置中固定方向:

import RNCamera from 'react-native-camera';

<RNCamera
  ref={cameraRef}
  style={styles.cameraContainer}
  type={RNCamera.Constants.Type.back}
  // 强制相机按竖屏方向拍摄/预览
  orientation={RNCamera.Constants.Orientation.portrait}
  captureAudio={false}
/>

3. Android端补充配置

除了android:screenOrientation="portrait",完善activity的配置项避免锁定失效:

<!-- AndroidManifest.xml -->
<activity
  android:name=".MainActivity"
  android:screenOrientation="portrait"
  android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode|screenLayout|smallestScreenSize">
  <!-- 其他原有配置 -->
</activity>

4. iOS端补充配置

  • 全局锁定:在Info.plist中仅保留竖屏支持:
    <key>UISupportedInterfaceOrientations</key>
    <array>
      <string>UIInterfaceOrientationPortrait</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
      <string>UIInterfaceOrientationPortrait</string>
    </array>
    
  • 页面级锁定:无需修改Info.plist,依赖react-native-orientation-locker的页面锁定逻辑即可,但必须配合相机组件的方向设置。

三、验证顺序

  1. 先确认react-native-orientation-locker在相机初始化前完成竖屏锁定
  2. 检查相机组件的orientation属性是否设置为竖屏
  3. 最后核对原生端配置项是否正确

内容的提问来源于stack exchange,提问作者Ramanjeet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 11:10:14