[英]I am unable to use array elements in src attribute of img tag in React
I aim to render multiple images whose path I have already defined in an array called images.我的目标是渲染多个图像,我已经在一个名为图像的数组中定义了它们的路径。 But when I want to use it in the src attribute of an img tag , for some reason it does not renders the image, even though the path is correct.
但是当我想在 img 标签的 src 属性中使用它时,由于某种原因它不会呈现图像,即使路径是正确的。
The code that I wrote in the react component was as follows:我在反应组件中编写的代码如下:
let images=["../../../assets/temp.jpg", "../../../assets/temp2.jpg", "../../../assets/temp3.jpg"];
let n = images.length;
let imgArray = [];
for (let i = 0; i < n; i++) {
imgArray.push(<img src={images[i]} alt="image cover" />);
}
return(
<div>
{imgArray}
</div>
);
The above code does not render the image provided as a path in src.上面的代码不会渲染作为 src 中的路径提供的图像。 But if I import the path and then provide that imported element as the src, then it works fine.
但是,如果我导入路径,然后将该导入的元素提供为 src,那么它就可以正常工作。
The tech I have used in my project is React.js and Bootstrap我在项目中使用的技术是 React.js 和 Bootstrap
React uses JSX which cannot display arrays. In your code {imgArray}
is an array of images, which you now need to loop through and convert to a JSX component/element. React 使用无法显示 arrays 的 JSX。在您的代码中,
{imgArray}
是一个图像数组,您现在需要对其进行循环并转换为 JSX 组件/元素。
The best approach is to use the array.map
function built in to JS arrays.最好的方法是使用
array.map
function 内置于 JS arrays。
// use "const" not let if the var doesn't change
const imgArray = [
{
key: 'uniqueid1',
src: 'path/to/img.png',
},
];
return
<div>
{
imgArray.map(_img => <img
src={_img.src}
key={_img.key}
alt="image cover"
/>)
}
</div>
);
You'll note we now don't need the for loop either.您会注意到我们现在也不需要 for 循环。
PS: Don't forget the "key" it's very important for React to reconcile the image elements you have created (and don't use the array index either)
PS:不要忘记“关键”,这对 React 协调您创建的图像元素非常重要(也不要使用数组索引)
More info:更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.