问题描述
我希望它仅在选择卡时播放,如果未选择该卡,它只会显示彩票文件但没有播放任何内容。现在我收到错误 cannot read property 'play' of null
。当我删除 animationPress()
并让文件运行时,它也会从我传递给它的提到的 initialSegment
开始。
我在这里做错了什么?
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>
</>
)
})}
...
)
编辑
我还尝试为 useState
和 autoplay
按钮执行 loop
所以它们会是假的但是当按钮被按下时它会变成 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 animation
已定义(非空),以便即使未启动容器也可以安装,这也适用于您的 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,height: 100 }} />}
当然还有
const animationPress = () => {
if(animation?.current) {
animation.current.play();
}
}