Ana*_*dis 5 reactjs next.js lottie
我在 NextJS 项目中使用 lottie JSON 文件来显示其中一些很酷的动画。
问题是 Lottie JSON 文件很大,确实降低了应用程序的性能。有没有人找到一种方法来使用这些动画,而不会将其项目的性能得分减半?
我在我的个人网站(下面的链接)上使用它们,lottie 文件位于服务部分(如果您滚动到下面一点)。初始页面加载感觉有点慢,我真的很想找到解决方案。
Dan*_*ila 21
您可以异步(动态)加载库和动画 json,如下所示:
import { useEffect, useRef, useState } from 'react';
import type { LottiePlayer } from 'lottie-web';
export const Animation = () => {
const ref = useRef<HTMLDivElement>(null);
const [lottie, setLottie] = useState<LottiePlayer | null>(null);
useEffect(() => {
import('lottie-web').then((Lottie) => setLottie(Lottie.default));
}, []);
useEffect(() => {
if (lottie && ref.current) {
const animation = lottie.loadAnimation({
container: ref.current,
renderer: 'svg',
loop: true,
autoplay: true,
// path to your animation file, place it inside public folder
path: '/animation.json',
});
return () => animation.destroy();
}
}, [lottie]);
return (
<div ref={ref} />
);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12572 次 |
| 最近记录: |