React Native 在循环中链接多个动画

8ftvxx2r  于 2022-12-24  发布在  React
关注(0)|答案(1)|浏览(147)

我正在尝试将两个动画链接在一起形成一个动画循环。首先文本向左移动,然后我想用另一个动画回到它的原始位置。
我尝试在moveRight()中的Animated.timing中添加回调,但没有成功。
这是我现在的代码,基本上我只是想把moveRight()和moveLeft()粘贴在一起。

export default function App() {
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const secondFadeAnim = useRef(new Animated.Value(100)).current;

  const moveRight = () => {
      Animated.timing(fadeAnim, {
        toValue: 0,
        duration: 5000
    }).start();
  }

  const moveLeft = () => {
    Animated.loop(
      Animated.timing(fadeAnim, {
        toValue: -250,
        duration: 5000
      })).start();}
  
  

  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>
                <Animated.View
          style={{
            transform: [{translateX: fadeAnim}]
          }}
        >
          <Text
          style={styles.title}
          >
          </Text>
        </Animated.View>
      </View>
      {moveLeft()}
    </SafeAreaView>
  );
}
4ioopgfo

4ioopgfo1#

如果我没理解错的话,你要做的就是让你的文字循环移动,向左,然后向右,再向左......
如果是这样的话,你应该可以通过合成一些小动画来实现。
此外,如果您希望在组件渲染后立即触发动画,则应将其放入useEffect中。
因此,重构动画,并将其放入useEffect

// ...
useEffect(() => {
    const moveRight = Animated.timing(fadeAnim, {
      toValue: 0,
      duration: 5000,
    });
    
    const moveLeft = Animated.timing(fadeAnim, {
      toValue: -250,
      duration: 5000,
    });

    Animated.loop(Animated.sequence([moveLeft, moveRight]), -1).start();
  }, [fadeAnim]);
// ...

基本上,我们正在创建两个动画序列的无限循环:moveLeftmoveRight
希望这有帮助!

相关问题