React Native中Image组件URI加载异常:‘Failed to construct Image’报错求助
React Native Image组件报错:Failed to construct 'Image': Please use the 'new' operator
问题描述
我正在学习React Native,跟着官方入门指南学习。当我尝试创建一个包含图片的自定义组件时,组件时而正常工作时而报错。我查了资料,有人说这和React Native的图片加载方式有关,它不支持动态加载?
我的代码如下:
class CuteImage extends Component { render() { return ( <View> <Image source={{uri: 'https://cdn1.medicalnewstoday.com/content/images/articles/322/322868/golden-retriever-puppy.jpg'}} /> </View> ); } } export default class ExampleComponent extends Component { render() { return ( <View style={{alignItems: 'center', justifyContent: 'center', flex: "1", flexDirection: "column"}}> <CuteImage /> </View> ); } }
我原本以为这段代码能正常运行,因为在官方Image组件教程里看到过类似的实现,但实际运行时抛出了错误:Failed to construct 'Image': Please use the 'new' operator。
请问这是什么原因导致的?这和图片的动态加载、静态加载有什么关联吗?
回答
别担心,这个报错和图片的动态/静态加载关系不大,核心问题出在命名冲突上!
你大概率是忘记从react-native包中显式导入Image组件了!如果没导入,JS引擎会把你写的<Image>标签当成浏览器环境里的原生Image构造函数去调用——而原生的Image对象必须用new关键字来实例化,这就直接触发了那个报错。
修复方法超简单:
在你的组件文件最顶部,补上必要的导入语句:
// 先导入React和Component import React, { Component } from 'react'; // 再从react-native导入View和Image组件 import { View, Image } from 'react-native';
另外给你提个小建议:React Native是完全支持网络图片(也就是你这种用uri的动态加载方式)的,但你需要给Image组件设置明确的宽高样式,不然图片可能加载出来了也看不到。比如可以修改你的Image代码:
<Image source={{uri: 'https://cdn1.medicalnewstoday.com/content/images/articles/322/322868/golden-retriever-puppy.jpg'}} style={{width: 300, height: 200}} />
总结一下,你遇到的问题和动态加载半毛钱关系都没有,就是漏了组件导入导致的命名冲突,补上导入就能解决啦!
内容的提问来源于stack exchange,提问作者Michael Szer
相关产品推荐
相关产品推荐

