在React应用程序中实现lottie动画

问题描述 投票:0回答:1

我有lottie动画作为

json
,我正在使用react-lottie在我的页面中为它们设置动画。

我有 4 件物品,如下所示:

 const items = [
        {
            animationData: layer1Animation,
            title: 'social gaming experiences',
            description: 'we develop entertaining engagement formats on the best social gaming platforms. We are platform agnostic, being able to build experiences on Roblox, Fortnite, Minecraft as well as custom proprietary solutions using Unreal Engine and Unity',
        },
        // and others
 ];

我有一个名为

activeIndex
的状态,每 3 秒更新一次索引:

    const [activeIndex, setActiveIndex] = useState(0);

    useEffect(() => {
        const interval = setInterval(() => {
            setActiveIndex((prevIndex) => (prevIndex + 1) % items.length);
        }, 3000);
        return () => clearInterval(interval);
    }, [items.length]);

以及 Lottie 的

defaultOptions
对象:

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

最后我将

jsx
渲染为:

<div className={styles.container}>
            <h3>but what are our actual solutions?</h3>
            <div className={styles.cart_items}>
                {items.map((item, index) => (
                    <div
                        key={index}
                        className={`${styles.cart_item} ${index === activeIndex ? styles.active : styles.inactive}`}
                    >
                        <div className={styles.image_container}>
                            <Lottie options={defaultOptions} />
                        </div>
                        <div className={styles.content}>
                            <p>{item.title}</p>
                            <span>{item.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>

问题是它没有按我的预期工作,动画有点关闭,因此当索引更改时它不会启动(或更改为下一个动画)。

应该如何:

desired result

您还可以在此codesandbox查看代码。

javascript reactjs lottie
1个回答
0
投票

动画可能小于或大于指定的超时时间,请尝试使用 onComplete 事件侦听器而不是超时

eventListeners=[
  {
    eventName: 'complete',
    callback: onComplete,
  },
]

链接:https://github.com/chenqingspring/react-lottie?tab=readme-ov-file#props

© www.soinside.com 2019 - 2024. All rights reserved.