react-native - 动画在本机反应中无法正常工作
问题描述
我尝试通过观看教程制作轮播,但我无法让它用于事件驱动的动画。而不是动画它只是将位置更新到新位置。
如果我只使用一种类型的动画进行过渡,则不会发生这种情况,只提到一个值来变换旋转而不是传递表达式。
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, 1],
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>
</>
)
}
解决方案
您的插值不应在 open 和 close 函数之间改变。动画库知道,当你从 0 到 1 时,你正在将块“旋转”出来,然后当你从 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>
</>
);
};
推荐阅读
- javascript - 将自定义组件作为触发器传递时,语义的弹出窗口不显示
- android - 如何根据 Android 项目构建类型(生产与暂存)配置哨兵环境?
- borland-c++ - TEdit - 如果剪贴板包含特定字符串,则忽略粘贴操作
- javascript - firebase.auth().signInAnonymously() 如何维护会话?
- vba - 如何为带有幻灯片时间和标题的 PowerPoint 视频制作生成 YouTube 索引?
- sql - 如何为已创建的 PostgreSQL 表创建外键?
- tcp - tcp_retransmit_skb 的 kprobe。而不是 tcp_retransmit_skb @tcp_states,我想 kprobe __napi_schedule
- java - 过滤器不响应意图
- excel - 我需要使用 vba 将链接发布到 Excel 表中
- arrays - Array 2d VBA 可选元素