警告:失败的道具类型:提供给`Image`的无效道具`source`

时间:2018-02-12 01:35:01

标签: javascript react-native

我的项目中有这个警告:“警告:失败的道具类型:提供给source的道具Image无效”。我正在将sampleProducts.json中的图像加载到Recommendend.js并将其作为Products.js中的道具传递,但由于警告,图像将无法加载。

sampleProducts.json

"recommended": {
    "product1": {
        "id": "1",
        "image": "require('../images/sample1.png')",
        "name": "Sample Product",
    },

Recommmended.js

{Object.values(recommended).map(product => (
                    <Products
                        key={ product.id }
                        productImage={ product.image }
                        productName={ product.name }
                    />
                ))}

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>

2 个答案:

答案 0 :(得分:0)

摆脱require()上的recommended.product1.image并将其设为“../ images / sample1.jpg”

将您的Image组件的源代码更改为 source={require(`${recommended.product1.image}`)}

答案 1 :(得分:0)

您不能以JSON格式使用 require 要求不支持动态路径。

您可以使用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");
  }
}

并将JSON更改为

"recommended": {
    "product1": {
        "id": "1",
        "image": "sample1.png",
        "name": "Sample Product",
    }
}

并使用下面的组件

<Image source={getImage(productImage)} />

如果您不想使用切换案例,请检查此answers以获取其他方法