我正在尝试使用map()方法呈现存储在数组中的图像。不幸的是,当我试图渲染数组中的图像时,我得到了错误,但是没有使用映射,我可以渲染图像,但是我需要逐行编写代码。有人能帮我解决这个问题吗?
const CardList = ({robots}) => {
const cardComponent = robots.map((user, i) => {
return <Card src={robots[i].src} id={robots[i].id} name={robots[i].name} email={robots[i].email}/>
})
return(
<div>
{cardComponent}
</div>
);我的CardList组件
const Card = ({name, email, id, src}) => {
return(
<div className='bg-light-green dib br3 pa3 ma2 grow bw db w-20'>
<img className='personal ' alt='robots' src={require(`${src}`)}/>
<div>
<h1>{name}</h1>
<p>{email}</p>
</div>
</div>
)我的卡组件我觉得src={require(${src})}有问题
这是我从react DOM得到的错误:

发布于 2020-05-30 01:39:53
yourArray.map((key, data) => {
<ComponentToDisplay id={key} {...this.props} />
});发布于 2020-05-30 06:05:03
TLDR;
// All of these works
const fileNameExt = 'foo.jpg'
<img src={require('../images/' + fileNameExt)} />
<img src={require(`../images/${fileNameExt}`)} />
const fileName = 'foo'
<img src={require('../images/' + fileName + '.jpg')} />
<img src={require(`../images/${fileName}.jpg`)} />
// These does not work:
const myPathVariable1 = '../images/' + 'foo' + '.jpg'
<img src={require(myPathVariable1)} />
const myPathVariable2 = '../images/' + 'foo.jpg'
<img src={require(myPathVariable2)} />
Explanation:You can not pass a variable name as argument to require,因为webpack没有做程序流分析来知道变量值。
因为无法提取(猜测)有关您在变量中提供的模块的任何信息(路径),所以Webpack无法知道它应该加载哪个模块。因此,当参数是变量时,it加载失败。
但是,如果您正确地提供了require with expression,它可以提取有关路径的一些信息,因此,是可以require with expression的。
例如,假设这是目录结构:
example_directory
│
└───template
│ │ table.ejs
│ │ table-row.ejs
│ │
│ └───directory
│ │ another.ejs方法1:使用变量(不起作用):
var myPath = './template/table-row.ejs'
require(myPath)
// will not work as webpack can't extract anything path or file as myPath is just a variable方法2:使用表达式(这是可行的;涉及到一些webpack可以理解的模式):
var myPath = 'table'
require("./template/" + name + ".ejs")通过方法二中的表达式,Webpack可以解析并生成以下上下文:
Directory: ./template // webpack understand that there is this directory
Regular expression: /^.*\.ejs$/ // and this regex about the modules因此,它将加载所有匹配的模块:
./template/table.ejs
./template/table-row.ejs
./template/directory/another.ejs
// Note that it will load all matching even if we provide --> var myPath = 'table' shown above因此,每当webpack在require中看到"expression“(而不是变量)时。它加载所有匹配的模块并生成"Context Module“,作为上述表达式的结果,它具有所有这些加载的模块的信息。
因此,您需要提供一个webpack能够理解的表达式,并通过加载所有匹配项来进行上下文模块。
这意味着支持dynamic requires,但会导致所有匹配的模块都包含在包中。(并且可能会增加包的大小,因此在使用require中的表达式时需要小心)
回答你的问题:
要使其工作,请执行以下操作:
<img className='personal' alt='robots' src={require(`${src}`)}/>您需要做的是:
<img className='personal' alt='robots' src={require("../images/" + src)}/>
// loads everyting inside "../images/"或者,better
<img className='personal' alt='robots' src={require("../images/" + src + ".png")}/>
// loads everything inside "../images/" ending with ".png"您也可以使用反引号,即template literals:
`../images/${src}.png`https://stackoverflow.com/questions/62091386
复制相似问题