如何在React.js中预加载图像? [英] How to preload images in React.js?

查看:833
本文介绍了如何在React.js中预加载图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在React.js中预加载图像?
我有下拉选择组件,其功能类似于菜单,但我必须预先加载项目的图像图标,因为有时它们在首次打开时不可见。

How to preload images in React.js? I have dropdown select component which works like menu , but i have to preload image icons for items,because sometimes they are not visible on first open.

I尝试过:

https://github.com / sambernard / react-preload

https://github.com/wizardzloy/react-img-preload

第一个有很好的API易于理解和使用,但是是spaming控制台警告图像未加载,即使它们是。
第二个有奇怪的API,但我尝试了一些例子并且它没有预加载任何东西。

First one has nice API easy to understand and use ,but is spaming console with warning that images were not loaded even when they were. Second one has strange API ,but I tried example and it did not preload anything.

所以我可能需要自己实现一些东西,但不要知道从哪里开始。或者另一种可能性就是用webpack加载它们。

So I probably need to implement something at my own ,but do not know where to start. Or another possibility would be to loaded them with webpack.

推荐答案

假设你有图片:string [] ; - 在组件的道具中定义的图片网址数组。
你应该在组件中定义componentDidMount()方法,然后为你想要预加载的每张图片创建新的Image对象:

Supposing you have pictures: string[]; - array of pictures urls defined in your component's props. You should define componentDidMount() method in your component and then just create new Image object for each picture you want to be preloaded:

componentDidMount() {
    this.props.pictures.forEach((picture) => {
        const img = new Image();
        img.src = picture.fileName;
    });
}

它强制浏览器加载所有图像。
这个例子是用TypeScript编写的。

It forces browser to load all images. This example is written in TypeScript.

这篇关于如何在React.js中预加载图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆