React组件报错‘Element type is invalid’求解决方案
解决React Native「Element type is invalid」错误
错误信息
Uncaught Error: 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.
问题场景
实现CompanyIcon组件时触发上述错误,已确认组件为默认导出,怀疑与react-native-svg相关。组件代码如下:
import React from 'react'; import { SvgFromUri } from 'react-native-svg'; import { Image } from 'react-native'; import { AppColors } from '../constants'; const imgSize = 55; const CompanyIcon = ({ url }) => { return ( <> { url && !url.includes('favicon') ? <SvgFromUri uri={url} width={imgSize} height={imgSize} onError={console.error} /> : <Image source={require('../assets/app_icon48.png')} style={ { borderWidth: 1, borderColor: AppColors.LIGHT_BLUE, borderRadius: 4, width: imgSize, height: imgSize } } /> } </> ); } export default CompanyIcon;
排查与解决方案
1. 修正react-native-svg组件导入
react-native-svg官方提供的从URI加载SVG的组件是SvgUri,而非SvgFromUri——导入不存在的组件会导致undefined,触发错误。修正后代码:
import React from 'react'; import { SvgUri } from 'react-native-svg'; import { Image } from 'react-native'; import { AppColors } from '../constants'; const imgSize = 55; const CompanyIcon = ({ url }) => { return ( <> {url && !url.includes('favicon') ? <SvgUri uri={url} width={imgSize} height={imgSize} onError={console.error} /> : <Image source={require('../assets/app_icon48.png')} style={{ borderWidth: 1, borderColor: AppColors.LIGHT_BLUE, borderRadius: 4, width: imgSize, height: imgSize }} /> } </> ); } export default CompanyIcon;
2. 验证react-native-svg安装与链接
- 确认版本适配:运行
npm list react-native-svg查看版本,确保与你的React Native版本兼容。 - 重新安装并清除缓存:
npm uninstall react-native-svg && npm install react-native-svg npx react-native start --reset-cache - 旧版React Native(<0.60)需手动链接:
react-native link react-native-svg
3. 确认组件导入方式
使用CompanyIcon时需用默认导入,避免命名导入:
// 正确写法 import CompanyIcon from './path/to/CompanyIcon'; // 错误写法(禁止使用) import { CompanyIcon } from './path/to/CompanyIcon';
4. 针对已知bug的临时方案
若上述步骤无效,可尝试降级react-native-svg至稳定版本,或改用WebView加载SVG资源作为替代方案。
内容的提问来源于stack exchange,提问作者rafakwolf
相关产品推荐
相关产品推荐

