Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset a react-native animation?

I've made some simple animation using Animated from react-native The animation works as expected after the first onPress, but I can't figure out how to reset it, to make it work for the next taps.

constructor(props) {
    super(props);
    this.spinValue = new Animated.Value(0);
    // Second interpolate beginning and end values (in this case 0 and 1)
    this.spin = this.spinValue.interpolate({
        inputRange: [0, 1, 2, 3, 4],
        outputRange: ['0deg', '4deg', '0deg', '-4deg', '0deg']
    });
}

handlePress() {
    // First set up animation 
    Animated.timing(
        this.spinValue,
        {
            toValue: 4,
            duration: 300,
        }
    ).start();
}

And in render

<TouchableWithoutFeedback onPress={() => { this.handlePress(); }} >
                    <Animated.Image
                        source={someImg}
                        style={{ height: undefined, width: undefined, flex: 1, transform: [{ rotate: this.spin }, { perspective: 1000 }] }}
                        resizeMode={'contain'}
                        resizeMethod="resize"
                    />
</TouchableWithoutFeedback>

Any suggestions? Thanks

like image 383
Cristian Tr Avatar asked Aug 06 '18 16:08

Cristian Tr


People also ask

How do I stop animation in react native?

If an animation is in process of being animated and, for any particular reason, you need to stop it, you can call stopAnimation . The stopAnimation call also takes a callback with the value that the animation was stopped on. this. _animatedValue = new Animated.

How do you check if animation is finished react native?

The updated answer should be: . start(({finished}) => { if (finished) { console. log('animation ended!) } })

What is diffClamp?

diffClamp() ​It uses the difference between the last value so even if the value is far from the bounds it will start changing when the value starts getting closer again. ( value = clamp(value + diff, min, max) ).

How do you loop animation in react native?

In order to create looping animations in react native, we should use Animated. loop() method. Wrap your Animations within Animated. loop() and the animations will act as a loop.


1 Answers

You can use this.spinValue.setValue(0) to reset it. You can add it at the beginning of handlePress.

like image 112
Antoine Grandchamp Avatar answered Sep 18 '22 20:09

Antoine Grandchamp