umijs如何使用封装好的Lottie动画
lottie:设计师制作动画,并提供json文件。前端可以使用对应的api操作时间流,对动画进行一些事件上的操作。
官网文档: https://github.com/airbnb/lottie-web
一. 下载依赖
npm install lottie-web
二. 在组件内引用
import lottie from 'lottie-web';
三.引入json文件
Lottie默认读取Assets中的文件,我们需要把设计导出的动画文件.json 保存在app/src/main/assets文件里。
四.构建Animation组件
例:
import React, { useRef, useEffect } from 'react';
import lottie from 'lottie-web';
import { connect } from 'umi';
import classNames from 'classnames';
const Animation = ({ className, visible, style, animationData, onInit }) => {
const el = useRef();
const animationInstances = useRef();
const duraction = animationInstances.current?.getDuration?.(true);
function init() {
if (!animationData) return;
animationInstances.current = {};
if (typeof animationData === 'function') {
animationData().then(initAnimate);
} else {
initAnimate(animationData);
}
function initAnimate(animationData) {
animationInstances.current = lottie.loadAnimation({
container: icon, // 包含动画的dom元素
renderer: 'svg', //渲染出来的是什么格式
loop: true, //循环播放
autoplay: true, //自动播放
path: './data.json' // 动画json的路径
});
onInit?.(animationInstances.current); }
}
useEffect(() => {
return () => {
// eslint-disable-next-line no-unused-expressions
// animationInstances.current?.destroy?.();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (animationInstances.current || !visible) return;
init();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [visible]);
//
return (
<div
ref={el}
style={{ visibility: !visible && 'hidden', ...style }}
className={classNames('lottie-animate', className)}
>
</div>
);
};
function mapStateToProps() {
return {
};
}
export default connect(mapStateToProps)(Animation);
4.在需要使用的页面引入Animation组件
import Animation from '文件路径';
const animation = () => import('@/assets/文件路径');
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构