Lottie文件动画播放时选择(博览会)



我希望它只在纸牌被选中时播放,如果纸牌没有被选中,它只是显示lottie文件,但没有播放任何内容。现在我得到cannot read property 'play' of null的误差。当我删除animationPress()并让文件运行时,它也会从我传递给它的提到的initialSegment开始。

我在这里做错了什么?

Lottie文件所在的卡片:

const animation = useRef(null);
const animationPress = () => {
animation.current.play();
}
return(
{filteredData.map((item, index) => {
return (
<>
<TouchableOpacity onPress={() => setSelected(item), animationPress()}>
<View style={[{ alignItems: 'center' }, selected.id == item.id ? { paddingTop: 10 } : { paddingTop: 20 }]}>
<CardioCard style={selected.id == item.id ? { backgroundColor: 'green', fontFamily: 'ssb_SemiBold' } : {}} >
<CardItem style={[styles.card, selected.id == item.id ? { backgroundColor: 'green' } : {}]}>
<Text>
< LottieView
ref={animation}
source={require('../../assets/images/heartbeat.json')}
initialSegment={68,135}
autoPlay={true}
loop={true}
style={{ width: 100, height: 100 }} />

</Text>
</CardItem>
</CardioCard>
<Text style={[{ fontSize: 18, color: 'hsl(98, 0%, 11%)', paddingLeft: 15 }, selected.id == item.id ? { fontFamily: 'ssb_SemiBold' } : {}]}>{item.name}</Text>
</View>
</TouchableOpacity>
</>
)
})}
...
)

编辑我也试着为autoplayloop按钮做useState,所以它们将是假的,但是当按钮被按下时,它会变成true,但是动画即使在按钮按下后也不会加载。

const [playAnimation, setPlayAnimation] = useState(false);
<TouchableOpacity onPress={() => setPlayAnimation(true)}>
<LottieView
source={require('../../assets/images/heartbeat.json')}
autoPlay={playAnimation}
loop={playAnimation}
style={{ width: 100, height: 100 }}
/> 
</TouchableOpacity>

这简直要把我逼疯了,我不知道该怎么办了。

我是react-native的新手,但我猜它就像react。不确定是否正确理解问题

在这种情况下,你不应该使用animation.current而不是animation作为你的lottieView ref?或者至少确保你的refanimation是定义的(不是null),这样即使没有启动容器也可以挂载,这也是你的animationPress函数。我猜你也应该禁用autoPlay(因为你想用一个按钮触发动画)。

< LottieView
ref={animation.current}
source={require('../../assets/images/heartbeat.json')}
initialSegment={68,135}
autoPlay={false}
loop={true}
style={{ width: 100, height: 100 }} />

{animation && < LottieView
ref={animation}
source={require('../../assets/images/heartbeat.json')}
initialSegment={68,135}
autoPlay={false}
loop={true}
style={{ width: 100, height: 100 }} />}

当然还有

const animationPress = () => {
if(animation?.current) {
animation.current.play();
}
}

最新更新