这篇文章跟大家分享一下 Lottie 动画在 React 中的控制与运用,Lottie 动画的源数据是一个 JSON 文件,我们可以通过 Lottie 库可以将其转换为动画效果
1npm install lottie-react
安装完成之后,我们可以通过 ref 获取到 Lottie 动画的控制句柄,并调用其实例对象的 play、pause、stop、goToAndStop 等方法来控制动画的播放
基础的运用如下所示
01import { useRef } from 'react';02import Lottie, { LottieRefCurrentProps } from 'lottie-react';03import carAnim from './lottie/car-loading-data.json';0405export default function Demo01() {06const lottieRef = useRef<LottieRefCurrentProps>(null);0708const __playHandler = () => {09lottieRef.current?.play();10};1112const __pauseHandler = () => {13lottieRef.current?.pause();14};1516return (17<div className="flex flex-col items-center py-8">18<Lottie lottieRef={lottieRef} animationData={carAnim} className="w-full" loop autoPlay />19<div className="flex mt-4 gap-4">20<button className="button" type="button" onClick={__playHandler}>播放</button>21<button className="button" type="button" onClick={__pauseHandler}>暂停</button>22</div>23</div>24);25};
在实践开发中,将 Lottie 动画用于 Tab 切换的图标,是非常常见的做法。我们可以基于 Lottie 进行二次封装,实现一个支持 Lottie 动画的 NavItem 组件
完整的代码如下所示
01import { useState, useRef } from 'react';02import { LottieRefCurrentProps } from 'lottie-react';03import NavItem from './nav-item';0405import dashboardAnim from './lottie/dashboard.json';06import settingsAnim from './lottie/setting.json';07import userAnim from './lottie/user.json';0809export default function BottomNavigation() {10const [activeTab, setActiveTab] = useState<number>(0);11const l1Ref = useRef<LottieRefCurrentProps | null>(null);12const l2Ref = useRef<LottieRefCurrentProps | null>(null);13const l3Ref = useRef<LottieRefCurrentProps | null>(null);1415function __clickHandler(index: number) {16const list = [l1Ref, l2Ref, l3Ref];17list[activeTab]?.current?.goToAndStop(0, true);18list[index]?.current?.play();19setActiveTab(index);20}2122return (23<div className="p-4">24<div className="flex justify-around items-center h-16">25<NavItem ref={l1Ref} animationData={dashboardAnim} isActive={activeTab === 0} label="Dashboard" onClick={() => __clickHandler(0)} loop={false} autoplay />26<NavItem ref={l2Ref} animationData={settingsAnim} isActive={activeTab === 1} label="Settings" onClick={() => __clickHandler(1)} loop={false} autoplay={false} />27<NavItem ref={l3Ref} animationData={userAnim} isActive={activeTab === 2} label="User" onClick={() => __clickHandler(2)} loop={false} autoplay={false} />28</div>29</div>30);31};
这里需要注意的是,我们在封装 NavItem 时,初次渲染时,ref 为 null,需要二次获取 Lottie 的实例句柄,因此,在内部我们定义了一个 loading 状态,结合 useEffect 来确保 ref 句柄的传递是有效的