[英]Warning: Failed prop type: Invalid prop `source` supplied to `Image`
I have this warning in my project: "Warning: Failed prop type: Invalid prop source
supplied to Image
". 我的项目中有以下警告:“警告:道具类型失败:提供给
Image
道具source
无效”。 I'm loading an image from sampleProducts.json to Recommendend.js and pass it as props in Products.js, but the image won't load because of the warning. 我正在将图像从sampleProducts.json加载到Recommendend.js并将其作为props传递给Products.js,但是由于警告,该图像将无法加载。
sampleProducts.json sampleProducts.json
"recommended": {
"product1": {
"id": "1",
"image": "require('../images/sample1.png')",
"name": "Sample Product",
},
Recommmended.js Recommmended.js
{Object.values(recommended).map(product => (
<Products
key={ product.id }
productImage={ product.image }
productName={ product.name }
/>
))}
Products.js Products.js
<Card style={ styles.card }>
<CardItem>
<Image style={ styles.productImage } source={ productImage} resizeMode='contain' />
</CardItem>
<CardItem>
<Body>
<Text style={ styles.productName }>{productName}</Text>
</Body>
</CardItem>
</Card>
Get rid of the require()
on recommended.product1.image
and make it just "../images/sample1.jpg" 摆脱对
recommended.product1.image
的require()
并将其变成“ ../images/sample1.jpg”
Change your Image
component's source prop to be source={require(`${recommended.product1.image}`)}
将您的
Image
组件的源道具更改为source={require(`${recommended.product1.image}`)}
You cannot use require in JSON format and require not support dynamic path. 您不能使用JSON格式的require ,并且require不支持动态路径。
Can you use switch case statement instead ? 您可以改用switch case语句吗?
function getImage(img_name) {
switch(img_name) {
case "sample1.png": return require("../images/sample1.png");
case "sample2.png": return require("../images/sample2.png");
}
}
and change JSON to 并将JSON更改为
"recommended": {
"product1": {
"id": "1",
"image": "sample1.png",
"name": "Sample Product",
}
}
and use with component below 并与下面的组件一起使用
<Image source={getImage(productImage)} />
If you don't want to use switch case check this answers for other methods 如果您不想使用开关盒,请检查其他方法的答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.