我试图将带有方法的 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.
block 引用>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
)
});
关于javascript - 保存动画实例以供以后使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72862709/