【问题标题】:Loading a Lottie animation with images in React在 React 中加载带有图像的 Lottie 动画
【发布时间】:2019-04-03 12:05:11
【问题描述】:

我正在尝试在我的 React 项目中包含 Lottie 动画。它成功加载 Lottie 组件,但没有图像。它无法解决资产。但是,它以 json(动画数据)和包含图像的图像目录的形式提供给我。

我试图解决这个问题的方法是将 json 数据放在一个 javascript 文件中,这个 js 文件导入所有图像并在 json 数据中使用这些导入。这样,React 将为这些图像解析正确的路径。我现在面临的问题是我似乎无法正确地将这个 javascript 文件导入/提供到 Lottie 组件的 animationData 属性。

这是我到目前为止所得到的。结果是Uncaught Error: Cannot find module '../../assets/animations/background-animation/animation.js'

BackgroundAnimation.tsx

import * as React from 'react';
import Lottie from 'react-lottie';
import animationData from '../../assets/animations/background-animation/animation.js';

export default class BackgroundAnimation extends React.Component {

    constructor(props) {
      super(props);
      this.state = {isStopped: false, isPaused: false};
    }

    render() {  
      const defaultOptions = {
        loop: true,
        autoplay: true, 
        animationData: animationData,
        rendererSettings: {
          preserveAspectRatio: 'xMidYMid slice'
        }
      };

      return <Lottie options={defaultOptions}/>
    }
  }

animation.js

import img_0 from './images/img_0.png'
import img_1 from './images/img_1.png'
...

export default {
    "v": "5.4.4",
    "fr": 30,
    "ip": 0,
    "op": 930,
    "w": 1920,
    "h": 1080,
    "nm": "TV - landscape",
    "ddd": 0,
    "assets": [
        {
            "id": "image_0",
            "w": 2349,
            "h": 1134,
            "u": "",
            "p": img_0,
            "e": 0
        },
        {
            "id": "image_1",
            "w": 1138,
            "h": 1139,
            "u": "",
            "p": img_1,
            "e": 0
        },
        ...
     ]
}

【问题讨论】:

    标签: javascript reactjs typescript lottie


    【解决方案1】:

    像上面那样导出它,然后像这样创建一个组件(我假设你在 React 中):

    import React from 'react';
    import Lottie from 'react-lottie';
    
    import animation from './animation';
    
    const Animation = ({ animePaused }) => {
      return (
        <Lottie
          options={{
            animationData: animation,
            autoplay: true
          }}
          height={200}
          isStopped={animePaused}
        />
      );
    };
    
    export default Animation;
    

    【讨论】:

    • 这没有回答问题。
    猜你喜欢
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 2020-07-04
    • 2019-01-06
    • 2020-01-10
    • 2019-11-30
    相关资源
    最近更新 更多