Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/470.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将映射变量放入图像的源中_Javascript_Reactjs_React Native_Ecma - Fatal编程技术网

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

Javascript 将映射变量放入图像的源中,javascript,reactjs,react-native,ecma,Javascript,Reactjs,React Native,Ecma,我已经搜索了整个堆栈,似乎并没有人根据我想要实现的目标来问这个问题。我正在通过一个数组进行映射,我想将映射变量的名称作为图像的源,也就是说,我将它与.jpg 这是我在下面尝试的,但它会导致以下错误调用require只需要1个字符串文字参数,但发现:require('./'+herb.name+'.jpg'),,我可能做错了什么 const herbs = this.state.record.map((herb) => <View key={herb.id} style={Back

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

这是我在下面尝试的,但它会导致以下错误
调用
require
只需要1个字符串文字参数,但发现:
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>
        );
const herbs=this.state.record.map((herb)=>
{herb.name}{herb.bot}
);

无法作为图像使用的资源需要预先静态地知道,以便解析器知道从何处加载资源

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

更多信息

var-imageMap={
“herb1”:require('path.to.img.jpg'),
“herb2”:require('path.to.img.jpg'),
};
您可以尝试的另一个选项是uri属性
您可以使用uri属性在项目的资源文件夹中定义动态图像

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


您遇到了什么错误?
调用
require`只需要一个字符串文字参数,但发现:
require(“./”+herb.name+“.jpg”)
`所以我不能使用对象名作为图像的源?不,您可以创建一个映射函数/对象,其中包含预先定义的所有资源,我要做的是编辑“path.to.img”,这是我的主要目标是,只是更新第二个选项的答案,你可以尝试一下
<Image source={{uri: `${herb.name}.jpg`}} />