从 staticFile() 加载 Lottie 动画
为了从放置在 public/
文件夹中的文件加载 Lottie 动画,请结合使用 staticFile()
、fetch
和 Remotion 的 delayRender()
函数。
使用 LottieAnimationData
类型来保持状态,使用 React 的 useState()
,并且仅在数据被获取后渲染 <Lottie>
组件。
Animation.tsxtsx
import {Lottie ,LottieAnimationData } from "@remotion/lottie";import {useEffect ,useState } from "react";import {cancelRender ,continueRender ,delayRender ,staticFile ,} from "remotion";constSquare = () => {const [handle ] =useState (() =>delayRender ("Loading Lottie animation"));const [animationData ,setAnimationData ] =useState <LottieAnimationData | null>(null);useEffect (() => {fetch (staticFile ("data.json")).then ((data ) =>data .json ()).then ((json ) => {setAnimationData (json );continueRender (handle );}).catch ((err ) => {cancelRender (err );});}, [handle ]);if (!animationData ) {return null;}return <Lottie animationData ={animationData } />;};
Animation.tsxtsx
import {Lottie ,LottieAnimationData } from "@remotion/lottie";import {useEffect ,useState } from "react";import {cancelRender ,continueRender ,delayRender ,staticFile ,} from "remotion";constSquare = () => {const [handle ] =useState (() =>delayRender ("Loading Lottie animation"));const [animationData ,setAnimationData ] =useState <LottieAnimationData | null>(null);useEffect (() => {fetch (staticFile ("data.json")).then ((data ) =>data .json ()).then ((json ) => {setAnimationData (json );continueRender (handle );}).catch ((err ) => {cancelRender (err );});}, [handle ]);if (!animationData ) {return null;}return <Lottie animationData ={animationData } />;};