我试图将Lottie对象与稍后使用的方法(另一个useEffect)保存到状态,但状态说它是空的。
我想用动物。playSegments方法
洛蒂文档。
更新#1:尝试将动画包含到依赖数组和事件侦听器中以检查动画是否已加载,但这没有帮助,并且应用程序导致循环。
动画现在无限加载
更新# 2:在useEffect之外声明一个变量,并在其中定义它。摆脱了国家方法。动画仍然是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;
您需要等待lottie加载完成。您可以通过监听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事件我使用lottie的内置方法" geregisteredanimations"解决了这个问题。在第二个useEffect钩子和解析数组的第一个元素,这是我的动画。
然后我把它存储到一个变量中,我可以用它来操纵我的动画。这是一种变通方法,但它有效。如果谁有更好的方法,不要犹豫地分享。
下面是最后的代码: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'
})
// This bit worked from the beginning
anim.playSegments(
(colorMode === 'dark'
? startToMid
: midToEnd), true
)
}, []);
useEffect(() => {
anim = lottie.getRegisteredAnimations()[0]
//anim no longer throws null
anim.playSegments(
(colorMode === 'dark'
? startToMid
: midToEnd), true
)
}, [colorMode])
return (
<>
<div>
ref={container}
onClick={toggleColorMode}
</div>
</>
)
}
export default ColorMode;