问题描述
我尝试通过观看教程制作轮播,但无法将其用于事件驱动的动画。无需对其进行动画处理,只需将位置更新为新位置即可。
如果我仅使用一种类型的动画进行过渡,而只提及一种值来变换旋转而不是传递表达式,则不会发生这种情况。
const cards = ["tomato","teal","pink"]
const alpha = Math.PI/6
const Trans = () => {
const value = React.useRef(new Animated.Value(0)).current
const [toggled,setToggled] = React.useState(false)
const animationFn = () => {
Animated.spring(value,{
tovalue: 1,friction: 10,useNativeDriver: true
}).start()
setToggled(toggled => !toggled)
}
const rotateOpen = (rotate) => {
return value.interpolate({
inputRange: [0,1],outputRange: ['0rad',`${rotate}rad`]
})
}
const rotateClose = (rotate,maxValues) => {
return value.interpolate({
inputRange: [0,outputRange: [`${maxValues}rad`,`${rotate}rad`]
})
}
return(
<>
{cards.map((card,index) => {
const rotate = toggled ? (index - 1) * alpha : 0
const maxValues = (index-1) * alpha
return (
<Animated.View key={card} style={{transform: [
{translateY: -50},{translateX: -100},{rotate: !toggled ? rotateOpen(rotate) : rotateClose(rotate,maxValues) },{translateX: 100},],borderRadius: 15,position: 'absolute',backgroundColor: card,height: 100,width: 200}} />
)
})}
<View style={{paddingTop: 100}}>
<TouchableOpacity onPress={() => { animationFn() }}>
<Text style={{fontSize: 30}}> Animate </Text>
</TouchableOpacity>
</View>
</>
)
}
解决方法
您的插值值不应在打开和关闭功能之间改变。动画库知道,当您从0转到1时,您将块“ out”旋转,然后当您从1转到0时,您将反向应用相同的插值
所以此代码似乎对我来说正常工作:
const Trans = () => {
const value = React.useRef(new Animated.Value(0)).current;
const [toggled,setToggled] = React.useState(false);
useEffect(() => {
Animated.spring(value,{
toValue: toggled ? 0 : 1,friction: 10,useNativeDriver: false,}).start();
},[toggled,value]);
return (
<>
{cards.map((card,index) => {
const rotate = (index - 1) * alpha;
return (
<Animated.View
key={card}
style={{
transform: [
{ translateY: -50 },{ translateX: -100 },{
rotate: value.interpolate({
inputRange: [0,1],outputRange: ['0rad',`${rotate}rad`],}),},{ translateX: 100 },],borderRadius: 15,position: 'absolute',backgroundColor: card,height: 100,width: 200,}}
/>
);
})}
<View style={{ paddingTop: 100 }}>
<TouchableOpacity
onPress={() => {
setToggled(!toggled);
}}>
<Text style={{ fontSize: 30 }}> Animate </Text>
</TouchableOpacity>
</View>
</>
);
};