You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在react-image-turntable中添加图片加载效果或进度条

给react-image-turntable添加加载效果/进度条的方案

实现思路

解决图片加载时页面为空的核心是预加载所有图片并跟踪加载状态,根据状态切换显示加载组件或转盘组件:

  • 用状态管理已加载图片数量与加载状态
  • 遍历图片列表,创建Image实例监听加载完成/失败事件
  • 根据加载进度渲染自定义加载效果(进度条、动画等)
  • 所有图片加载完成后渲染ReactImageTurntable

完整组件代码

import { useState, useEffect } from 'react';
import ReactImageTurntable from 'react-image-turntable';

const YourTurntableComponent = () => {
  const [rotationDisabled, setRotationDisabled] = useState(false);
  const [loadedCount, setLoadedCount] = useState(0);
  const [images, setImages] = useState([/* 你的图片URL数组 */]);
  const totalImages = images.length;
  const isLoading = loadedCount < totalImages;

  // 预加载图片
  useEffect(() => {
    if (totalImages === 0) return;
    
    let loaded = 0;
    images.forEach(imgUrl => {
      const img = new Image();
      img.src = imgUrl;
      img.onload = () => {
        loaded++;
        setLoadedCount(loaded);
      };
      // 处理图片加载失败的情况
      img.onerror = () => {
        loaded++;
        setLoadedCount(loaded);
        console.error(`图片加载失败: ${imgUrl}`);
      };
    });

    // 清理函数,避免组件卸载后更新状态
    return () => {
      loaded = totalImages;
    };
  }, [images, totalImages]);

  const handleKeyDown = (e) => {
    // 你的键盘事件处理逻辑
  };

  // 自定义加载进度组件
  const renderLoading = () => {
    const progress = (loadedCount / totalImages) * 100;
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '400px' }}>
        <div style={{ width: '80%', height: '10px', backgroundColor: '#eee', borderRadius: '5px' }}>
          <div 
            style={{ 
              width: `${progress}%`, 
              height: '100%', 
              backgroundColor: '#4CAF50', 
              borderRadius: '5px',
              transition: 'width 0.3s ease'
            }} 
          />
        </div>
        <p style={{ marginTop: '1rem' }}>加载中... {Math.round(progress)}%</p>
      </div>
    );
  };

  return (
    <>
      {isLoading ? renderLoading() : (
        <ReactImageTurntable
          images={images}
          autoRotate={{ disabled: rotationDisabled, interval: 200 }}
          onPointerDown={() => setRotationDisabled(true)}
          onPointerUp={() => setRotationDisabled(false)}
          onKeyDown={handleKeyDown}
          onKeyUp={() => setRotationDisabled(false)}
        />
      )}
    </>
  );
};

export default YourTurntableComponent;

关键说明

  • 预加载逻辑:通过useEffect遍历图片URL,创建Image对象监听onload事件,每加载完成一张就更新loadedCount
  • 加载状态判断:isLoading通过已加载数量与总数量的对比,判断是否处于加载阶段
  • 自定义加载效果:renderLoading实现了基础进度条,你可以根据需求替换成加载动画、骨架屏等
  • 错误处理:添加onerror事件处理单张图片加载失败的情况,避免因个别图片问题导致加载状态一直无法完成

内容的提问来源于stack exchange,提问作者Edson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 01:47:11