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

如何在React Native Expo移动端更改视频播放器的屏幕方向

在React Native Expo中实现视频播放器屏幕方向切换

步骤1:安装依赖

首先安装用于控制屏幕方向的expo-screen-orientation包:

npx expo install expo-screen-orientation

步骤2:配置Android权限(推荐)

在app.json中添加Android方向控制权限:

{
  "expo": {
    "android": {
      "permissions": ["android.permission.REQUEST_SCREEN_ORIENTATION"]
    }
  }
}

步骤3:修改代码实现方向切换

更新组件代码,集成屏幕方向控制逻辑:

import { Video } from "expo-av";
import React, { useState, useRef, useEffect } from "react";
import { StyleSheet, View } from "react-native";
import * as ScreenOrientation from 'expo-screen-orientation';

export default function App() {
  const video = useRef(null);
  const [status, setStatus] = useState({});
  const [isLandscape, setIsLandscape] = useState(false);

  // 组件卸载时恢复竖屏
  useEffect(() => {
    return () => {
      ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT_UP);
    };
  }, []);

  // 监听原生控件的全屏切换事件
  const handleFullscreenUpdate = async ({ fullscreenUpdate }) => {
    if (fullscreenUpdate === Video.FULLSCREEN_UPDATE_PLAYER_DID_PRESENT) {
      await ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.LANDSCAPE);
      setIsLandscape(true);
    } else if (fullscreenUpdate === Video.FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS) {
      await ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT_UP);
      setIsLandscape(false);
    }
  };

  return (
    <View style={styles.container}>
      <Video
        ref={video}
        style={isLandscape ? styles.videoLandscape : styles.video}
        source={{
          uri: "http://d23dyxeqlo5psv.cloudfront.net/big_buck_bunny.mp4",
        }}
        useNativeControls
        resizeMode="contain"
        isLooping
        onPlaybackStatusUpdate={setStatus}
        onFullscreenUpdate={handleFullscreenUpdate}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#000',
  },
  video: {
    width: '100%',
    height: 280,
  },
  videoLandscape: {
    width: '100%',
    height: '100%',
  },
});

关键说明

  • 用ScreenOrientation.lockAsync锁定屏幕方向,支持PORTRAIT_UP(竖屏)、LANDSCAPE(横屏)等模式
  • 通过onFullscreenUpdate监听原生视频控件的全屏切换事件,自动同步屏幕方向
  • 组件卸载时恢复竖屏,避免影响其他页面的方向设置
  • 根据isLandscape状态动态调整视频组件样式,确保横屏时占满整个屏幕

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:43:19