Reputation: 48490
I am attempting to put the following animation in an infinite loop until a particular state occurs:
class MyModal extends Component {
constructor() {
super()
this.springValue = new Animated.Value(0.3)
}
spring = () => {
this.springValue.setValue(0.3)
Animated.spring(
this.springValue,
{
toValue: 1,
friction: 1,
tension: 1,
duration:5000
}
).start()
}
componentDidMount() {
this.spring()
}
render() {
return (
<View>
<Modal
animationType="none"
transparent={false}
visible={this.state.modalVisible}
onRequestClose={() => null}
>
<View style={styles.backgroundStyle}>
<Animated.Image
source={require("./my-awesome-image.png")}
style={{ width: 143, height: 125, top: 100, transform: [{scale: this.springValue}]}}
/>
</View>
</Modal>
</View>
);
}
}
Everything here works great, the animation completes once (as I'm not looping anywhere).
How do I keep my Animated.Image
looping until I reach a particular state? I just want it infinite looping and the ability to either stop the animation or start another animation when I'm ready to.
Upvotes: 4
Views: 11746
Reputation: 1977
Pass a callback to the start function to check whether to restart the animation. You could break it down to something like this:
onSpringCompletion = () => {
if (arbitraryCondition) {
this.spring();
}
}
spring = () => {
this.springValue.setValue(0.3)
Animated.spring(
this.springValue,
{
toValue: 1,
friction: 1,
tension: 1,
duration:5000
}
).start(this.onSpringCompletion);
}
Upvotes: 3
Reputation: 3102
Store your animation in a variable you can access and just wrap your animation with Animated.loop()
. Then you can freely use .start()
and .stop()
on that variable holding the animation as you please.
So something like this should do:
this.springAnimation = Animated.loop(
Animated.spring(
this.springValue,
{
toValue: 1,
friction: 1,
tension: 1,
duration:5000
}
).start()
)
You can find more information about that here:
https://facebook.github.io/react-native/docs/animated.html#loop
Upvotes: 12
Reputation: 397
You can use setInterval to keep the animation playing and remove the interval whenever you want. I would do this:
componentDidMount() {
this.interval = setInterval(() => this.spring(), 5000) // Set this time higher than your animation duration
}
...
// Some where in your code that changes the state
clearInterval(this.interval)
...
Upvotes: -3