【问题标题】:loading lottie-web animation in react issue在反应问题中加载lottie-web动画
【发布时间】:2019-01-06 05:52:06
【问题描述】:

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

InvalidStateError:responseText 仅在 responseType 为 '' 或 '文档'。

下面是我的 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,只写path: "email.json"
  • @Tholle 谢谢!将路径更改为/email.json 并将文件放在我的公用文件夹中就可以了。我假设它必须在公用文件夹中才能访问网络请求?
  • 太棒了!是的,这是对的。 public 文件夹中的所有内容都将从 / 提供。我认为这只是引擎盖下的app.use(express.static('public'))

标签: javascript reactjs lottie


【解决方案1】:

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} />;
  }
}

【讨论】:

  • 如果我想用storybook显示动画怎么办?我需要一个正在运行的本地服务器来提供文件吗?
【解决方案2】:

您可以使用 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
    });

【讨论】:

    猜你喜欢
    • 2020-07-04
    • 2020-01-10
    • 2023-02-17
    • 1970-01-01
    • 2018-03-23
    • 2019-11-30
    • 2020-03-05
    • 2022-11-10
    • 1970-01-01
    相关资源
    最近更新 更多