首页 > 解决方案 > 如何使用 map() 方法从数组中渲染图像?

问题描述

我正在尝试使用该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}有问题)}

这是我从反应 DOM 得到的错误: 错误

标签: reactjs

解决方案


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)} />


说明: 您不能将变量名称作为参数传递给 require,因为 webpack 不会进行程序流分析来了解变量值。

Webpack 无法知道它应该加载哪个模块,因为它无法提取(猜测)有关您在变量中提供的模块的任何信息(路径)。因此,当参数是 variable 时,它​​无法加载

但是,webpack 可以要求 with 表达式,因为如果您正确提供它,它可以提取有关路径的一些信息。

例如,假设这是目录结构:

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 可以从方法 2 中的表达式解析并生成以下上下文

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. 它加载所有匹配的模块并生成一个“上下文模块”,其中包含所有此类加载模块的信息作为上述表达式的结果。

因此,您需要提供一个 webpack 可以理解的表达式,并通过加载所有匹配项来制作上下文模块。

这意味着支持动态需求,但会导致捆绑包中包含所有匹配的模块。(并且可能会增加你的包大小,所以在使用 require 中的表达式时需要小心)


回答你的问题:

为了使这项工作:

<img className='personal' alt='robots' src={require(`${src}`)}/>

你需要做:

<img className='personal' alt='robots' src={require("../images/" + src)}/>
// loads everyting inside "../images/"

或者,更好

<img className='personal' alt='robots' src={require("../images/" + src + ".png")}/>
// loads everything inside "../images/" ending with ".png"

您也可以使用反引号,即模板文字

`../images/${src}.png`

推荐阅读