如何修复React Native中react-native-video的TypeError: Cannot read property 'Constants' of null
问题:react-native-video 抛出TypeError: Cannot read property 'Constants' of null
错误信息
ERROR TypeError: Cannot read property 'Constants' of null
复现代码
import React, { useRef, useState } from 'react'; import { View, Text, StyleSheet } from 'react-native'; import Video from 'react-native-video'; const App = () => { const videoRef = useRef(null); const onBuffer = (e) => { console.log('buffering..', e); }; const onError = (e) => { console.log('error..', e); }; return ( <View style={styles.container}> <Video source={{ uri: 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4', }} ref={(ref) => { videoRef.current = ref; }} onBuffer={onBuffer} onError={onError} style={styles.backgroundVideo} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, }, backgroundVideo: { position: 'absolute', top: 0, left: 0, bottom: 0, right: 0, }, }); export default App;
问题定位
这个错误本质是react-native-video的原生模块未正确链接,导致JS层无法访问原生模块的Constants属性,常见于自动链接失效、版本不兼容或缓存问题。你的代码逻辑本身没有错误,问题出在原生层的集成环节。
解决方案
1. 确认版本兼容性
- 检查
react-native-video版本与你的React Native版本是否匹配:- React Native 0.60+ 需使用
react-native-video@5.x及以上版本 - 运行
npm list react-native-video查看当前版本,若不匹配,卸载重装对应版本:npm uninstall react-native-video npm install react-native-video@适配版本号
- React Native 0.60+ 需使用
2. 重新链接原生模块
iOS 端:
- 进入项目根目录下的
ios文件夹:cd ios - 删除现有Pod缓存并重新安装:
rm -rf Pods Podfile.lock pod install - 打开Xcode,执行
Command+Shift+K清理Build文件夹,然后重新编译运行
Android 端:
- 进入项目根目录下的
android文件夹:cd android - 清理Gradle缓存:
./gradlew clean - 重启Android Studio,清理项目缓存(
File → Invalidate Caches / Restart)后重新编译
3. 手动验证链接配置(自动链接失效时)
iOS:
检查ios/Podfile中是否包含以下配置,若没有则添加后重新执行pod install:
pod 'react-native-video', :path => '../node_modules/react-native-video'
Android:
- 检查
android/settings.gradle:include ':react-native-video' project(':react-native-video').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-video/android') - 检查
android/app/build.gradle的dependencies块:implementation project(':react-native-video') - 检查
MainApplication.java(若RN版本低于0.60):import com.brentvatne.react.ReactVideoPackage; @Override protected List<ReactPackage> getPackages() { return Arrays.asList( new MainReactPackage(), new ReactVideoPackage() // 添加这一行 ); }
4. 清除项目全局缓存
- 删除
node_modules并重新安装依赖:rm -rf node_modules npm install # 或 yarn install - 重置Metro缓存:
npx react-native start --reset-cache
完成以上步骤后重新运行项目,错误应该会被解决。
内容的提问来源于stack exchange,提问作者Shivanshu Bhashkar
相关产品推荐
相关产品推荐

