将映射变量放入图像的源中

Putting mapped variable in source for an Image

我搜索了堆栈,似乎没有人根据我想要实现的目标来问这个问题。我正在通过一个数组进行映射,我想将映射变量的名称作为图像的来源,即将它与 .jpg

连接起来

这是我在下面尝试的,但它带来了这个错误 calls torequireexpect exactly 1 string literal argument, but this was found:require('./' + herb.name + '.jpg'). ,我可能做错了什么

 const herbs = this.state.record.map((herb) =>
 <View key={herb.id} style={BackStyles.herb_box}>
 <Image style={BackStyles.image} source={require('./'+herb.name+'.jpg')}/>
 <View style={{flexDirection: 'column',}}><Text style={BackStyles.header}>{herb.name}</Text> <Text style={BackStyles.sub}>{herb.bot}</Text></View>
            </View>
        );

这行不通,因为图像需要预先静态知道,因此解析器知道从哪里加载资产。

为了使其工作,必须静态知道 require 中的图像名称。

更多信息here

var imageMap = {
    "herb1":  require('path.to.img.jpg'),
    "herb2":  require('path.to.img.jpg'),
};
<Image style={BackStyles.image} source={imageMap[herb.name]}/>

您可以 尝试 的其他选项是 uri 属性
您可以使用 uri 属性 在项目的资源文件夹中定义动态图像。

<Image source={{uri: `${herb.name}.jpg`}} />