Table of Contents

1、概述

这篇文章跟大家分享一下 Lottie 动画在 React 中的控制与运用,Lottie 动画的源数据是一个 JSON 文件,我们可以通过 Lottie 库可以将其转换为动画效果

shell
1
npm install lottie-react

安装完成之后,我们可以通过 ref 获取到 Lottie 动画的控制句柄,并调用其实例对象的 playpausestopgoToAndStop 等方法来控制动画的播放

基础的运用如下所示

预览
index.tsx
01
import { useRef } from 'react';
02
import Lottie, { LottieRefCurrentProps } from 'lottie-react';
03
import carAnim from './lottie/car-loading-data.json';
04
05
export default function Demo01() {
06
const lottieRef = useRef<LottieRefCurrentProps>(null);
07
08
const __playHandler = () => {
09
lottieRef.current?.play();
10
};
11
12
const __pauseHandler = () => {
13
lottieRef.current?.pause();
14
};
15
16
return (
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
};

2、Tab 切换

在实践开发中,将 Lottie 动画用于 Tab 切换的图标,是非常常见的做法。我们可以基于 Lottie 进行二次封装,实现一个支持 Lottie 动画的 NavItem 组件

完整的代码如下所示

预览
index.tsx
nav-item.tsx
01
import { useState, useRef } from 'react';
02
import { LottieRefCurrentProps } from 'lottie-react';
03
import NavItem from './nav-item';
04
05
import dashboardAnim from './lottie/dashboard.json';
06
import settingsAnim from './lottie/setting.json';
07
import userAnim from './lottie/user.json';
08
09
export default function BottomNavigation() {
10
const [activeTab, setActiveTab] = useState<number>(0);
11
const l1Ref = useRef<LottieRefCurrentProps | null>(null);
12
const l2Ref = useRef<LottieRefCurrentProps | null>(null);
13
const l3Ref = useRef<LottieRefCurrentProps | null>(null);
14
15
function __clickHandler(index: number) {
16
const list = [l1Ref, l2Ref, l3Ref];
17
list[activeTab]?.current?.goToAndStop(0, true);
18
list[index]?.current?.play();
19
setActiveTab(index);
20
}
21
22
return (
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 句柄的传递是有效的

专栏首页
到顶
专栏目录