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

React Native youtube iframe点击全屏按钮切换横屏及退出锁定问题解决

问题根因

你当前的逻辑依赖Dimensions判断屏幕方向来切换状态,没有使用react-native-youtube-iframe组件onFullScreenChange回调自带的全屏状态参数,状态判断和实际触发时机不匹配,导致退出全屏时方向切换逻辑出错。

修复方案

直接通过回调返回的布尔值判断当前是进入还是退出全屏,对应切换方向即可,同时给异步的方向锁定方法加上async/await避免竞态问题。

修复后的完整代码如下:

import React from "react";
import { View } from "react-native";
import YoutubePlayer from "react-native-youtube-iframe";

import * as ScreenOrientation from "expo-screen-orientation";

const VideoPlayer = () => {
  // 接收回调返回的全屏状态参数
  async function setOrientation(isFullScreen) {
    if (isFullScreen) {
      // 进入全屏,锁定横屏
      await ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.LANDSCAPE);
    } else {
      // 退出全屏,锁定竖屏
      await ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT);
      // 如果需要退出后允许用户自由旋转,可替换为下面的代码
      // await ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.UNKNOWN);
    }
  }

  return (
    <View
      style={{
        width: "100%",
        height: 220,
      }}
    >
      <YoutubePlayer
        height={300}
        play={false}
        videoId={"Dv7gLpW91DM"}
        onFullScreenChange={setOrientation}
      />
    </View>
  );
};

export default VideoPlayer;
注意事项
  • 请确保项目全局配置没有强制锁定方向:
    • iOS端:app.json的ios配置项下,UISupportedInterfaceOrientations需要同时包含竖屏和横屏的支持选项
    • Android端:app.json的android配置项下,不要设置固定的screenOrientation值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 08:15:03