How to preload images in React.js?

前端 未结 7 623
夕颜
夕颜 2020-12-10 11:14

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 visib

7条回答
  •  一生所求
    2020-12-10 11:18

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

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

提交回复
热议问题