reactjs - 如何在 React 中预加载图像?

标签 reactjs jsx

我有一组图像,例如

var imgsArray = [];
imgsArray[0] = new Image();
imgsArray[0].src = "https://upload.wikimedia.org/wikipedia/commons/b/b6/Queen_Elizabeth_II_in_March_2015.jpg";
imgsArray[1] = new Image();
imgsArray[1].src = "https://upload.wikimedia.org/wikipedia/commons/b/b6/Queen_Elizabeth_II_in_March_2015.jpg";

我想将此数组中的图像添加到 React 组件返回的 JSX 中。我该怎么做?

我尝试了以下方法:

<ImageList cols={1}>
  {imgsArray.map((img) => (
    <ImageListItem key={img.src}>
      img
    </ImageListItem>
</ImageList>

但是没有出现图像,也没有出现任何错误。

我还尝试在 img 周围放置大括号,即 {img} 并收到错误:

Uncaught Error: Objects are not valid as a React child (found: [object HTMLImageElement]). If you meant to render a collection of children, use an array instead.

最佳答案

实例化元素并设置 src 属性足以开始预加载图像,无需将其附加到 DOM。

const images = ['someImageUrl.jpg', 'someOtherImageUrl.jpg'];

for (const image of images) {
  const imageElement = new Image();
  imageElement.src = image;
}

<ImageList>
  {images.map((img) => (
    <ImageListItem key={img}>
      <img src={img} />
    </ImageListItem>
  ))}
</ImageList>

关于reactjs - 如何在 React 中预加载图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72493824/

相关文章:

javascript - 从javascript es6中的函数调用函数

javascript - 如何使用 React 从 ReqRes API 渲染用户列表

react-native - 如何在 React Native 中对齐标签和输入?

node.js - NodeJS/React : Taking a picture, 然后将其发送到mongoDB进行存储和稍后显示

ios - 在react-native-maps中动画结束后调用函数

reactjs - mapStateToProps 函数,定位帖子的 id 而不是所有帖子

javascript - 导出函数内部的对象

javascript - react : Pass component as prop without using this. props.children

javascript - 将数据属性传递给 DOM

javascript - 为所有组件 React-Native 设置不 header