React Native Reanimate:如何实现组件依次滑动动画?
解决两个独立对象的顺序滑动动画问题
针对你遇到的withSequence无法适配两个独立组件动画的问题,这里提供两种实用的解决思路:
方法1:利用动画完成回调触发下一个动画
这是最直接的方案,通过第一个动画的onComplete回调,在其执行完毕后启动第二个对象的动画。
代码示例(React Native Animated API)
import { Animated, View, StyleSheet, Button } from 'react-native'; import { useRef } from 'react'; function SequentialAnimatedObjects() { // 初始化两个独立的动画值 const obj1Pos = useRef(new Animated.ValueXY({ x: -200, y: -200 })).current; const obj2Pos = useRef(new Animated.ValueXY({ x: -200, y: -200 })).current; const startAnimations = () => { // 执行第一个对象的动画 Animated.timing(obj1Pos, { toValue: { x: 500, y: 200 }, duration: 1200, // 自定义动画时长 useNativeDriver: true, }).start(() => { // 第一个动画完成后,启动第二个对象的动画 Animated.timing(obj2Pos, { toValue: { x: 475, y: 180 }, duration: 1200, useNativeDriver: true, }).start(); }); }; return ( <View style={styles.container}> <Animated.View style={[styles.object, { transform: obj1Pos.getTranslateTransform() }]} /> <Animated.View style={[styles.object, { transform: obj2Pos.getTranslateTransform() }]} /> <Button title="启动顺序动画" onPress={startAnimations} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center' }, object: { width: 50, height: 50, backgroundColor: 'blue', margin: 10 } });
方法2:通过状态变量控制动画触发时机
如果需要更灵活的状态控制,可以用一个状态变量标记第一个动画的完成状态,再通过useEffect监听状态变化来启动第二个动画。
代码示例
import { Animated, View, StyleSheet, Button } from 'react-native'; import { useRef, useState, useEffect } from 'react'; function SequentialAnimatedObjects() { const obj1Pos = useRef(new Animated.ValueXY({ x: -200, y: -200 })).current; const obj2Pos = useRef(new Animated.ValueXY({ x: -200, y: -200 })).current; const [firstAnimFinished, setFirstAnimFinished] = useState(false); const startFirstAnim = () => { Animated.timing(obj1Pos, { toValue: { x: 500, y: 200 }, duration: 1200, useNativeDriver: true, }).start(() => setFirstAnimFinished(true)); }; // 监听第一个动画完成状态,启动第二个动画 useEffect(() => { if (firstAnimFinished) { Animated.timing(obj2Pos, { toValue: { x: 475, y: 180 }, duration: 1200, useNativeDriver: true, }).start(); } }, [firstAnimFinished]); return ( <View style={styles.container}> <Animated.View style={[styles.object, { transform: obj1Pos.getTranslateTransform() }]} /> <Animated.View style={[styles.object, { transform: obj2Pos.getTranslateTransform() }]} /> <Button title="启动顺序动画" onPress={startFirstAnim} /> </View> ); }
补充说明
withSequence的核心限制在于它仅能针对单个共享动画值执行连续的动画步骤,无法同时控制两个独立的动画变量。上面两种方案都是通过"先执行完第一个动画,再触发第二个"的逻辑,完美适配你的需求。
内容的提问来源于stack exchange,提问作者user23619834
相关产品推荐
相关产品推荐

