0

我正在写一个简单的动画,并在完成后尝试重置它

import React, { useState, useEffect } from 'react';
import { StyleSheet, View, Image, Animated, Easing } from 'react-native';

export default function App() {
  const [leftPos, setLeftPos] = useState(new Animated.Value(0))

  useEffect(() => {
    cycleAnimation()
  }, []);

  const cycleAnimation = () => {
    console.log('STARTING ANIMATION:', leftPos)
    Animated.sequence([
      Animated.timing(
        leftPos,
        {
          toValue: 430,
          duration: 3000,
          easing: Easing.linear,
          useNativeDriver: false
        }
      )
    ]).start(() => {
      setLeftPos(new Animated.Value(0))
      cycleAnimation()
    })
  }


  return (
    <View style={{ backgroundColor: 'black', flex: 1 }}>

      <Animated.View style={{ left: leftPos }}>
        <Image
          style={styles.cloud}
          source={require('./assets/cloud.png')}
        />
      </Animated.View>

    </View >
  );
}

const styles = StyleSheet.create({
  cloud: {

  }
});

尽管使用新的 0 值调用 setLeftPos,但在 cycleAnimation 中 leftPos 始终为 430(第一次迭代除外)。还尝试将 cycleAnimation 放入 setLeftPos 的回调中,但得到了相同的结果。

4

2 回答 2

1

您正在错误地重置它。无需更新状态,试试这个:

leftPos.setValue(0);

于 2020-12-22T21:21:15.387 回答
0

将您的功能放入 useEffect

import React, { useState, useEffect } from "react";
import { StyleSheet, View, Image, Animated, Easing } from "react-native";

export default function App() {
  const [leftPos, setLeftPos] = useState(new Animated.Value(0));

  useEffect(() => {
    const cycleAnimation = () => {
      console.log("STARTING ANIMATION:", leftPos);
      Animated.sequence([
        Animated.timing(leftPos, {
          toValue: 430,
          duration: 3000,
          easing: Easing.linear,
          useNativeDriver: false,
        }),
      ]).start(() => {
        setLeftPos(new Animated.Value(0));
      });
    };
    cycleAnimation();
  }, [leftPos]);

  return (
    <View style={{ backgroundColor: "black", flex: 1 }}>
      <Animated.View style={{ left: leftPos }}>
        <Image style={styles.cloud} source={require("./assets/icon.png")} />
      </Animated.View>
    </View>
  );
}

const styles = StyleSheet.create({
  cloud: {},
});
于 2020-12-22T21:40:59.777 回答