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/文件路径');
 
posted @   AllenPanni  阅读(191)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示