如何在React Native Animated循环中串联两个文本位移动画?
解决React Native动画循环串联问题
要实现文本先左移再回到初始位置的循环动画,你需要用Animated.sequence把两个动画串联起来,再用Animated.loop包裹这个序列。另外,直接在组件渲染时调用动画函数会导致每次重渲染都触发动画,应该用useEffect来初始化动画。
修正后的代码
import React, { useRef, useEffect } from 'react'; import { SafeAreaView, View, Text, Animated, StyleSheet } from 'react-native'; export default function App() { const fadeAnim = useRef(new Animated.Value(0)).current; // 定义串联的动画序列:先左移,再回到初始位置 const startLoopAnimation = () => { Animated.loop( Animated.sequence([ // 左移动画:从0到-250,耗时5秒 Animated.timing(fadeAnim, { toValue: -250, duration: 5000, useNativeDriver: true, // 启用原生驱动提升性能 }), // 回到初始位置:从-250到0,耗时5秒 Animated.timing(fadeAnim, { toValue: 0, duration: 5000, useNativeDriver: true, }) ]) ).start(); }; // 组件挂载后启动动画 useEffect(() => { startLoopAnimation(); }, []); const title = "This is some super long title it just keeps on going"; return ( <SafeAreaView style={styles.container}> <View style={styles.bord}> <Animated.View style={{ transform: [{ translateX: fadeAnim }], }} > <Text style={styles.title}>{title}</Text> </Animated.View> </View> </SafeAreaView> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, bord: { borderWidth: 1, overflow: 'hidden', // 避免文本溢出容器 width: 300, // 限制容器宽度,让动画效果更明显 }, title: { fontSize: 16, whiteSpace: 'nowrap', // 让文本不换行 }, });
关键说明
Animated.sequence:按顺序执行数组内的动画,只有前一个动画完成后才会启动下一个,精准实现"先左移再复位"的逻辑。useEffect:确保动画仅在组件挂载时启动一次,避免重复触发。useNativeDriver: true:启用原生动画驱动,提升动画流畅度,是React Native动画的最佳实践。- 移除了无用的
secondFadeAnim和空的Animated.View,简化代码结构。
关于之前回调无效的原因
如果之前尝试在Animated.timing的start()里加回调,正确写法应该是:
Animated.timing(fadeAnim, { toValue: -250, duration: 5000, }).start(() => { // 左移动画完成后执行复位动画 Animated.timing(fadeAnim, { toValue: 0, duration: 5000, }).start(); });
但这种写法要实现循环的话,需要在复位动画的回调里再次调用左移动画,不如直接用Animated.loop + Animated.sequence简洁可靠。
内容的提问来源于stack exchange,提问作者laxboy436
相关产品推荐
相关产品推荐

