在反应问题中加载 lottie-web 动画

loading lottie-web animation in react issue

我试图在我的 React 项目中加载一个 lottie-web 动画,但我一直收到此错误并且无法理解它的含义

InvalidStateError: responseText is only available if responseType is '' or 'document'.

下面是我的 React 组件:

import React, { Component } from "react";
import "./Submit.css";
import PropTypes from "prop-types";
import lottie from "lottie-web";

class Submit extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    lottie.loadAnimation({
      container: document.getElementById("animation"), // the dom element that will contain the animation
      renderer: "svg",
      loop: true,
      autoplay: true,
      path: "../anim/email.json" // the path to the animation json
    });
  }

  render() {
    return <div id="animation" />;
  }
}

Submit.propTypes = {};

export default Submit;

有什么想法吗?

path 应该是 lottie 可以通过网络请求获取 JSON 的路径,而不是文件系统路径。

通过将 email.json 放在 public 文件夹中,尝试在根目录中提供 email.json,并且只需将 "/email.json" 用作 path。您还可以在 render 方法中的元素上放置一个 ref 以使其成为完全模块化的组件。

例子

class Submit extends Component {
  ref = null;

  componentDidMount() {
    lottie.loadAnimation({
      container: this.ref,
      renderer: "svg",
      loop: true,
      autoplay: true,
      path: "/email.json"
    });
  }

  render() {
    return <div ref={ref => this.ref = ref} />;
  }
}

您可以使用 animationData 代替路径道具 lottie.loadAnimation 支持。 你唯一要做的就是把email.json文件转换成js文件,然后把里面的json对象保存成const。如果您导出此 const,然后将其导入到您要使用的文件中:

 //email.js file
const email = {
//the json object
}

export default email.



//your other file

import Email from "../anim/email.js"

 lottie.loadAnimation({
      // the dom element that will contain the animation
      container: document.getElementById("animation"), 
      renderer: "svg",
      loop: true,
      autoplay: true,
      animationData: Email // the path to the animation json
    });