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

React中Lottie动画切换滞后于内容加载的原因排查

React中react-lottie轮播动画切换延迟问题

场景说明

在React页面中使用react-lottie组件实现了一组Lottie动画轮播,支持自动切换与用户交互。通过items数组存储动画数据,每个元素包含animationData(Lottie JSON对象)、title和description字段。

代码实现

1. 动画数据数组

const items = [
    {
        animationData: layer1Animation,
        title: '社交游戏体验',
        description: '我们在主流社交游戏平台开发趣味互动形式...',
    },
    // 其他元素
];

2. Lottie默认配置

const defaultOptions = {
    loop: false,
    autoplay: true,
    animationData: items[activeIndex].animationData,
    rendererSettings: {
        preserveAspectRatio: 'xMidYMid slice',
    },
};

3. 动画完成事件监听

通过监听动画完成事件实现自动切换索引:

const eventListeners = [
    {
        eventName: 'complete',
        callback: handleAnimationComplete,
    },
];

const handleAnimationComplete = () => {
    setActiveIndex((prevIndex) => (prevIndex + 1) % items.length);
};

4. 页面渲染逻辑

渲染包含动画与内容的卡片,为Lottie组件设置key={activeIndex}确保索引切换时触发重渲染:

<div className={styles.container}>
    <h3>我们的实际解决方案是什么?</h3>
    <div className={styles.cart_items}>
         <div className={`${styles.cart_item} ${styles.active}`}>
             <div className={styles.image_container}>
                 <Lottie
                     key={activeIndex}
                     options={defaultOptions}
                     eventListeners={eventListeners}
                     height={400}
                 />
             </div>
             <div className={styles.content}>
                 <p>{items[activeIndex].title}</p>
                 <span>{items[activeIndex].description}</span>
             </div>
         </div>
    </div>
    <div className={styles.animation_slider}>
        {items.map((_, index) => (
            <div
                key={index}
                onClick={() => setActiveIndex(index)}
                className={index === activeIndex ? styles.active : styles.inactive}
            ></div>
        ))}
    </div>
</div>

问题现象

切换索引时,标题和描述内容会立即更新,但Lottie动画启动存在0.5秒以上的延迟,导致内容与动画不同步,用户体验不佳。

已尝试的方案

  • 配置动画完成事件监听切换索引,事件触发正常,但延迟问题未解决;
  • 为Lottie组件设置key={activeIndex}强制重渲染,未解决时序同步问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 17:35:16