简体   繁体   English

如何在 React 中预加载图像?

[英]How to preload images in React?

I have an array of images, eg我有一系列图像,例如

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";

I would like to add the images in this array to the JSX returned by a React component.我想将此数组中的图像添加到 React 组件返回的 JSX。 How do I do this?我该怎么做呢?

I tried the following:我尝试了以下方法:

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

But no images appeared, nor did any errors appear.但是没有图像出现,也没有出现任何错误。

I also tried placing curly braces around img ie {img} and received the error:我还尝试在img{img}周围放置花括号并收到错误:

Uncaught Error: Objects are not valid as a React child (found: [object HTMLImageElement]).未捕获的错误:对象作为 React 子项无效(找到:[object HTMLImageElement])。 If you meant to render a collection of children, use an array instead.如果您打算渲染一组子项,请改用数组。

Instantiating the element and setting the src property is enough to start preloading the image, there is no need to attach it to the DOM.实例化元素并设置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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM