javascript - 保存动画实例以供以后使用

标签 javascript reactjs react-hooks jsx lottie

我试图将带有方法的 Lottie 对象(另一个 useEffect)保存到状态中,但状态显示它为 null。

我想使用文档中指定的 anim.playSegments 方法。

洛蒂documentation .

Update #1: Tried including anim into the dependency array and event listener for checking if the animation has loaded, but that didn't help and the application resulted in a cycle.

Animation now loads indefinitely

Update #2: Declared a variable outside of the useEffect and defined it inside of it. Got rid of the state approach. Anim is still null.

import React, { useEffect, useRef, useState } from 'react';
import { useColorMode } from '@chakra-ui/react';
import lottie from 'lottie-web';
import animationData from '../assets/json/sun-to-night'

const ColorMode = () => {
  const container = useRef(null)
  const { colorMode, toggleColorMode } = useColorMode()

  // Segments of the animation
  const midToEnd = [14, 28]
  const startToMid = [0, 14]

  let anim = null

  useEffect(() => {
    anim = lottie.loadAnimation({
      container: container.current,
      animationData: animationData,
      autoplay: false,
      loop: false,
      name: 'anim'
    })

    // Here the animation instance exists and animation is played
    console.log(`${anim}`)
    anim.playSegments(
      (colorMode === 'dark'
        ? startToMid
        : midToEnd), true
    )
  }, []);

  useEffect(() => {
    //anim is null in here and the React app throws an error
    anim.addEventListener('DOMLoaded', () => {
      anim.playSegments(
        (colorMode === 'dark'
          ? startToMid
          : midToEnd), true
      )
    })
  }, [colorMode])


  return (
    <>
      <div>
          ref={container}
          onClick={toggleColorMode}
      </div>
    </>
  )
}

export default ColorMode;

最佳答案

您需要等待您的彩票加载完毕。您可以通过监听 DOMLoaded 事件来完成此操作:

 const anim = lottie.loadAnimation({
        container: container.current,
        animationData: animationData,
        autoplay: false,
        loop: false,
        name: 'anim'
      });

anim.addEventListener('DOMLoaded', () => {
  anim.playSegments(
        (colorMode === 'dark'
          ? startToMid
          : midToEnd), true
      )
});

更多内容请看这里: https://github.com/airbnb/lottie-web#events

关于javascript - 保存动画实例以供以后使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72862709/

相关文章:

javascript - 错误 : [ng:areq] from angular controller

json - 如何在 React 中导入 json 文件

javascript - 右键菜单触发其父菜单项的单击事件

javascript - 在类组件中绑定(bind)React实例方法

reactjs - 如何测试对 React 钩子(Hook)的依赖

javascript - 在事件监听器函数中无法访问 React hooks 值

javascript - 如何通过 CMS 控制 CSS pseudo::before 和::after 取决于文本是否在标题元素中?

javascript - AngularJS:当多条消息更改消息的 ngModel 时,警报不会显示

javascript - knockoutjs 映射插件从对象中删除功能

reactjs - 如何在 Typescript(输入组件)中使用 React Hook Form