React Native运行报Element type is invalid错误该如何解决?
错误触发原因
你遇到的报错本质是渲染了值为undefined的组件,具体触发点有两个:
- Canvas导入错误:React Native 核心库未内置Canvas组件,你直接从
react-native包中解构导入Canvas,得到的值为undefined,将undefined作为组件渲染直接触发报错。 - RNCamera导入方式错误:
react-native-camera包的RNCamera为默认导出,而非命名导出,你使用import { RNCamera } from "react-native-camera"的写法拿到的值也是undefined。
报错原文:Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports
修复方案
- 修正Canvas导入
如果需要使用Canvas能力,先安装第三方适配库react-native-canvas,再替换导入语句:
// 移除原来的import { Canvas } from 'react-native' import Canvas from 'react-native-canvas'
- 修正RNCamera导入
将RNCamera的导入语句改为默认导入写法:
// 移除原来的import { RNCamera } from "react-native-camera" import RNCamera from "react-native-camera"
- Expo项目额外适配
如果你使用Expo框架开发,推荐直接使用Expo官方维护的expo-camera替代react-native-camera,安装后调整导入和组件使用即可:
import { Camera } from 'expo-camera' // 组件标签同步改为 <Camera> 替换原来的 <RNCamera>
内容的提问来源于stack exchange,提问作者Tahmid Faisal
相关产品推荐
相关产品推荐

