React Native播放YouTube视频报错:TypeError: Cannot read property 'Constants' of undefined
解决React Native中播放YouTube视频时出现的TypeError: Cannot read property 'Constants' of undefined错误
错误原因分析
这个错误主要来自两个核心问题:
- Video组件依赖异常:你使用的
<Video>组件(通常是react-native-video)可能未正确安装、链接,或者版本与当前React Native版本不兼容,导致组件内部尝试访问Constants模块时找不到对应对象。 - YouTube视频源无效:直接使用YouTube的
watch格式链接作为视频源是行不通的,YouTube不允许第三方播放器直接加载这类链接,这会触发组件内部报错,进一步暴露依赖问题。
解决方案
1. 修复Video组件依赖(若坚持使用react-native-video)
如果要继续使用react-native-video,先重新安装并确保依赖正确:
# 卸载现有包 npm uninstall react-native-video # 重新安装 npm install react-native-video # iOS项目需执行pod安装 cd ios && pod install && cd ..
完成后重启Metro打包服务和模拟器/真机,确保依赖完全加载。
2. 替换为兼容YouTube的播放方案(推荐)
由于YouTube不支持直接通过普通视频播放器加载,推荐使用react-native-webview嵌入YouTube的embed链接,步骤如下:
- 先安装webview组件:
npm install react-native-webview
- 修改Modal中的视频播放部分:
import WebView from 'react-native-webview'; // ... 其他代码保持不变 {selectedVideo && ( <Modal animationType="slide" transparent={false} visible={!!selectedVideo} // 根据选中状态控制Modal显示 onRequestClose={closeModal} > <View style={styles.modalContainer}> <WebView source={{ uri: `https://www.youtube.com/embed/${selectedVideo}` }} style={styles.fullScreen} allowsFullscreenVideo={true} // 允许全屏播放 /> <TouchableOpacity style={styles.closeButton} onPress={closeModal}> <Text style={styles.closeText}>Close</Text> </TouchableOpacity> </View> </Modal> )}
3. 额外优化:修正Modal的visible属性
你之前的Modal写死了visible={true},这会导致Modal一直处于显示状态,改为visible={!!selectedVideo}可以根据选中状态正确控制Modal的显示隐藏。
内容的提问来源于stack exchange,提问作者Yanel Pinto
相关产品推荐
相关产品推荐

