功能需求:加载多图片项目的时候,想提供一个loading页面,让用户知道加载进度。
实现代码:
import React, {useEffect, useState} from 'react'; const imgLoad = ()=>{ // 要加载的图片资源 const picList = [ 'http://dummyimage.com/1000x1000/FF6611', 'http://dummyimage.com/1000x1000/FF6622', 'http://dummyimage.com/1000x1000/FF6633', 'http://dummyimage.com/1000x1000/FF6644', 'http://dummyimage.com/1000x1000/FF6655', 'http://dummyimage.com/2000x2000/FF6666', 'http://dummyimage.com/1000x1000/FF6677', 'http://dummyimage.com/1000x1000/FF6688', 'http://dummyimage.com/1000x1000/FF6699', 'http://dummyimage.com/1000x1000/FF66AA', 'http://dummyimage.com/1000x1000/FF66BB', 'http://dummyimage.com/1000x1000/FF66CC', ]; // 加载进度数值 const [loadNum, setLoadNum] = useState(0); const [showPicList, setShowPicList] = useState([]); // 加载处理函数 const loadFun = (arr=[], callback)=>{ let len = 0; let num = 0; callback(0) for(let i = 0; i < arr.length; i++){ (function(i){ const img = new Image(); img.src = arr[i]; img.onload = function(){ len ++; num = parseInt((len / arr.length) * 100); callback(num , len-1, img.src); } })(i); } } useEffect(()=>{ // 执行代码 loadFun(picList, (num, idx, src)=>{ if(src){ showPicList.push(src); setShowPicList(showPicList); setLoadNum(num); } }); },[]); return <> <div>加载进度:{loadNum}%</div> <div style={{'200px'}}> { showPicList.map((item, index)=>{ return <img key={item} width="50px" src={item} alt={'图片_'+(index+1)}/> }) } </div> </> } export default imgLoad;
功能截图: