React:在图像加载时显示加载微调器

blu*_*ris 11 image loading spinner reactjs

我有一个 React 应用程序,它调用useEffect我的 API,它返回一个 URL 列表,用作 imy 图像 srcs。

我正在使用react-loader-spinner在我的图像加载时显示加载微调组件。

我有一个loading变量useState来确定图像是否正在加载。

我不知道如何停止显示加载微调器并在它们全部加载后显示我的图像。

这是我的代码:

照片.jsx

import React, { useState, useEffect, Fragment } from 'react'
import Loader from 'react-loader-spinner';
import { getAllImages } from '../../services/media.service';
import Photo from '../common/Photo';

const Photos = () => {
  const [photos, setPhotos] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
      setLoading(true);
      getAllImages()
        .then(results => {
          setPhotos(results.data)
          console.log(results.data)
        })
        .catch(err =>{
          console.log(err)
        })
  }, [])

  const handleLoading = () => {
    setLoading(false)
  }

  return ( 
    <Fragment>
      <div className="photos">
          { loading ? 
            <Fragment>
              <Loader
                height="100"    
                width="100"
              />
              <div>Loading Joe's life...</div>
            </Fragment>
            :
            photos.map((photo, index) => (
                index !== photos.length - 1 ? 
                <Photo src={photo.src} key={photo.id} /> :
                <Photo src={photo.src} key={photo.id} handleLoad={handleLoading}/>
            ))
          }
      </div>
    </Fragment>
   );
}

export default Photos;
Run Code Online (Sandbox Code Playgroud)

照片.jsx

import React from 'react'

import './Photo.css';

const Photo = (props) => {
  return ( 
    <div className="photo">
      <img src={props.src} alt={props.alt} onLoad={props.handleLoad}/>
      <div className="caption">
        Photo caption
      </div>
    </div>
   );
}

export default Photo;
Run Code Online (Sandbox Code Playgroud)

我尝试使用onLoad我的最后一个项目,但它永远不会被调用,因为loading由于仍在显示微调器,它永远不会被设置回 false。

对此的一些帮助将不胜感激。谢谢

Kei*_*ith 27

之所以从未调用 onLoad,是因为您从未在 DOM 中拥有过图像,因此不是有条件地渲染,而是有条件地将 display 属性设置为 none & block。

下面是一个如何等待所有图像加载的简单示例。

可以安全地假设具有最大文件大小的图像很可能是最后加载的

肯定不是!!,加载图像所需的时间并不总是取决于大小、缓存或服务器负载会影响这些。

const {useState, useEffect, useRef} = React;

const urls = [
  "https://placeimg.com/100/100/any&rnd=" + Math.random(),
  "https://placeimg.com/100/100/any&rnd=" + Math.random(),
  "https://placeimg.com/100/100/any&rnd=" + Math.random()
];

function Test() {
  const [loading, setLoading] = useState(true);
  const counter = useRef(0);
  const imageLoaded = () => {
    counter.current += 1;
    if (counter.current >= urls.length) {
      setLoading(false);
    }
  }
  return <React.Fragment>
    <div style={{display: loading ? "block" : "none"}}>
       Loading images,
    </div>
    <div style={{display: loading ? "none" : "block"}}>
      {urls.map(url => 
        <img 
          key={url}
          src={url}
          onLoad={imageLoaded}/>)}
    </div>
  </React.Fragment>;
}

ReactDOM.render(<React.Fragment>
  <Test/>
</React.Fragment>, document.querySelector('#mount'));
Run Code Online (Sandbox Code Playgroud)
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="mount"></div>
Run Code Online (Sandbox Code Playgroud)


小智 5

只需像这样创建和组件并加载到您想要使用图像的任何地方:

import React from 'react'
import { useState } from 'react';

export default function MyImage({src, width, size}) {
    const [loading, setLoading] = useState(true);
    return (
    <div style={
        {
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            width: width?width:"100%",
        }
    } >
    <img src={src} style={
        {
            display: loading?"none":"block",
            width:"100%",
            animation: "fadeIn 0.5s",
        }
    } onLoad={(e)=>{setLoading(false)}}></img>
    <div className="spinner" style={{
        display: loading?"block":"none",
        fontSize: size?size:"24px"
    }} ></div>
</div>)}
Run Code Online (Sandbox Code Playgroud)

如果你想要更多的 ui 效果,你只需要定义一个 css 类作为微调器的“spinner”和一个动画作为图像的“fadeIn”。用法 :

<MyImage src="link/to/image" />
Run Code Online (Sandbox Code Playgroud)