React 的 Lottie 动画

2025-06-07

React 的 Lottie 动画

谁不喜欢动画呢?它们有趣、引人入胜、用途广泛。在这篇文章中,我将介绍Lottie动画以及如何将它们实现到你的 React 网站中。

什么是 Lottie?

Lottie 是一种基于 JSON 的动画文件格式,使设计师能够在任何平台上发布动画。它们文件很小,可以在任何设备上使用,并且可以缩放而不会出现像素化。

将 Lottie 集成到 React App

步骤1:安装库

npm install --save react-lottie

第 2 步:从LottieFiles中选择一个动画

您可以将其下载为 JSON 格式,也可以使用 Lottie 动画 URL。
我个人更喜欢将其下载并存储在应用程序的文件夹中。
以下是文件结构的示例:

步骤3:在src中创建Lottie.js文件

该文件内的代码应如下所示:

import React from "react";
import Lottie from "react-lottie";

export default function LottieAnimation({ lotti, width, height }) {
  const defaultOptions = {
    loop: true,
    autoplay: true,
    animationData: lotti,
    rendererSettings: {
      preserveAspectRatio: "xMidYMid slice",
    },
  };

  return (
    <div>
      <Lottie options={defaultOptions} height={height} width={width} />
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode
步骤 4:将 Lottie 导入到您想要返回动画的组件中:
import React from 'react';
import LottieAnimation from '../Lottie';
import home from '../Animation/dev.json';

const Example = () => {

    return ( 
         <div className='example'> 
           <LottieAnimation lotti={home} height={300} width={300} />
        </div>
    )
}

export default Example; 
Enter fullscreen mode Exit fullscreen mode

注意:此示例意味着您随后<Example />在 App.js 中添加渲染


就这样!你漂亮的 Lottie 动画现在应该渲染到你的网站上了!

与往常一样,欢迎反馈和讨论。💁

文章来源:https://dev.to/mariaverse/lottie-animations-for-react-1c9l
PREV
大 O 符号入门指南
NEXT
JavaScript 中的闭包