我在我的NextJS项目中使用lottie JSON文件来显示一些这些很酷的动画。
问题是lottie JSON文件是巨大的,真的降低了应用程序的性能。有没有人找到一种方法来使用这些动画的少数没有减半他们的项目的性能得分?
我在我的个人网站上使用它们(下面的链接),lottie文件位于服务部分(如果你在下面滚动一点)。最初的页面加载感觉有点慢,我真的很想找到一个解决方案。
https://stylidis.io
可以异步(动态)加载库和动画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} />
);
};
首先安装您的软件包npm install --save @lottiefiles/lottie-player
或简单地yarn add @lottiefiles/lottie-player
import React, { FC, useEffect, useRef } from 'react';
const YourCard: FC = () => {
const ref = useRef(null);
useEffect(() => {
import('@lottiefiles/lottie-player');
});
return (
<div>
<lottie-player
id="firstLottie"
ref={ref}
autoplay
mode="normal"
src="here your json link/find on lottie website"
/>
</div>
);
};
export default YourCard;
一定要在项目的根目录下添加一个名为declare .d.ts的声明文件
declare namespace JSX {
interface IntrinsicElements {
"lottie-player": any;
}
}
为了完成别人的答案,我创建了一个函数组件:(复制粘贴使用)
文件夹名为lotie/index.js
import * as React from 'react';
export default function Lotie({ src }) {
const ref = React.useRef();
const [lottie, setLottie] = React.useState(null);
React.useEffect(() => {
import('lottie-web').then(Lottie => setLottie(Lottie.default));
}, []);
React.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: src,
});
return () => animation.destroy();
}
}, [lottie]);
return <div ref={ref}></div>;
}
使用:
import Lotie from '../../components/common/lotie';
....
<Lotie src={'/lotiefiles/loading-house.json'} />
....