I would like to animate a view on press.
export default class AnimatedRotation extends React.Component {
constructor(props) {
super(props);
this.state = {
spinValue: new Animated.Value(0),
color: '#F62459',
}
}
rotateSpring = () => {
Animated.spring(
this.state.spinValue,
{
toValue: 1,
friction: 1,
}
).start();
this.setState({
color: this.state.color == '#F62469' ? '#FFC107' : '#F62469',
})
};
render() {
var spin = this.state.spinValue.interpolate({
inputRange: [0, 1],
outputRange: ['0deg', '360deg'],
});
return (
<View style={styles.container}>
<Text style={styles.header}>Header</Text>
<View style={styles.wrapper}>
<TouchableWithoutFeedback onPress={this.rotateSpring}>
<Animated.View style={[styles.circle, {
transform: [{rotate: spin},],
backgroundColor: this.state.color
}]}>
<Icon name="ios-add" color="white" size={50}/>
</Animated.View>
</TouchableWithoutFeedback>
</View>
</View>
);
}
}
But when I press its animating only once, and not animating again. I suppose its because, the state of spinValue
equals to the toValue
when its pressed for the first time. So I thought of doing something like this:
rotateSpring = () => {
Animated.spring(
this.state.spinValue,
{
toValue: this.state.spinValue + 1,
friction: 1,
}
).start();
this.setState({
color: this.state.color == '#F62469' ? '#FFC107' : '#F62469',
spinValue: this.state.spinValue + 1,
})
};
But this makes the app crash. How do I animate something onPress?
Very simple solution:
this.state.spinValue.setValue(0);
Animated.spring(...);
If your animation is cyclic (and it looks like it is) then you should be fine with simply running this line before starting the animation.
Comment: There's no reason for the Animated.Value to be a part of the state. A good hint for that is the fact that you never used setState() with it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With