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

React Native如何实现不同页面分别固定竖屏、横屏显示?

React Native 页面定向横竖屏切换最简实现方案

推荐使用成熟的第三方封装库 react-native-orientation-locker 实现,不需要自己编写原生代码,几步操作即可完成需求:

第一步:安装依赖

执行安装命令:

# npm 安装
npm install react-native-orientation-locker --save

# 或 yarn 安装
yarn add react-native-orientation-locker

安装完成后iOS端需要执行cd ios && pod install关联原生依赖。

第二步:基础原生配置

  • iOS端:打开ios目录下的Info.plist文件,确保UISupportedInterfaceOrientations字段下同时包含竖屏、横屏的支持项,否则定向锁定会失效
  • 安卓端:默认无需额外配置,部分定制系统如果出现锁定失效问题,可以在AndroidManifest.xml的主Activity标签中添加属性android:screenOrientation="fullSensor"

第三步:页面逻辑编写

以常用的React Navigation路由为例,在对应页面的生命周期钩子中调用方向锁定API即可:

首页(强制竖屏页)代码示例

import { useEffect } from 'react';
import Orientation from 'react-native-orientation-locker';
import { Button, View, Text } from 'react-native';

const HomeScreen = ({ navigation }) => {
  useEffect(() => {
    // 页面挂载时锁定为竖屏
    Orientation.lockToPortrait();
  }, []);

  return (
    <View style={{flex:1, justifyContent: 'center', alignItems: 'center'}}>
      <Text>这是竖屏首页</Text>
      <Button 
        title="跳转到横屏页"
        onPress={() => navigation.navigate('LandscapeScreen')}
      />
    </View>
  );
};

二级页(强制横屏页)代码示例

import { useEffect } from 'react';
import Orientation from 'react-native-orientation-locker';
import { Button, View, Text } from 'react-native';

const LandscapeScreen = ({ navigation }) => {
  useEffect(() => {
    // 页面挂载时锁定为横屏
    Orientation.lockToLandscape();
    // 页面卸载时切回竖屏,避免影响其他页面
    return () => Orientation.lockToPortrait();
  }, []);

  return (
    <View style={{flex:1, justifyContent: 'center', alignItems: 'center'}}>
      <Text>这是横屏二级页</Text>
      <Button 
        title="返回首页"
        onPress={() => navigation.goBack()}
      />
    </View>
  );
};

注意事项

  • 如果使用其他路由库,逻辑完全一致,只要保证页面获得焦点时锁定目标方向、失去焦点/卸载时恢复原有方向即可
  • 调用lockToLandscapeLeft或lockToLandscapeRight可以固定为左横屏或右横屏,如果不需要固定方向调用lockToLandscape即可跟随系统感应切换左右横屏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:09:04