如何在React Native中停止循环动画? [英] How to stop a looping animation in React Native?

查看:1301
本文介绍了如何在React Native中停止循环动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的组件中有一个简单的循环动画,如下所示:

  runAnimation(){
console.log ('运行动画');
this.state.angle.setValue(0);
Animated.timing(this.state.angle,{
toValue:360,
duration:8000,
easing:Easing.linear
})。start(( )=> this.runAnimation());
}

...

< Animated.Image
style = {[
styles.rotate,
{变换:[
{rotate:this.state.angle.interpolate({
inputRange:[0,360],
outputRange:['0deg','360deg']
}),
]}
]}
source = {require('./ spinning_ball.png')}
/>

如何停止此动画?例如,当导航到另一个屏幕或用户点击按钮后。



我尝试使用 this.state.angle.stopAnimation()但注意到运行动画仍然在控制台中打印。我应该调用一个不同的stop方法来阻止执行启动回调吗?

解决方案

根据我在Nguyên的评论Hoàng的回答。如果你调用 this.state.angle.stopAnimation()



<$ p,这是另一种停止循环动画的方法$ p> runAnimation(){
this.state.angle.setValue(0);
Animated.timing(this.state.angle,{
toValue:360,
duration:8000,
easing:Easing.linear
})。start(( o)=> {
if(o.finished){
this.runAnimation();
}
});
}


I have a simple looping animation in my component like this:

runAnimation() {
    console.log('run animation');
    this.state.angle.setValue(0);
    Animated.timing(this.state.angle, {
        toValue: 360,
        duration: 8000,
        easing: Easing.linear
    }).start(() => this.runAnimation());
}

...

<Animated.Image
    style={[
        styles.rotate,
        { transform: [
            { rotate: this.state.angle.interpolate({
                inputRange: [0, 360],
                outputRange: ['0deg', '360deg']
            })},
        ]}
    ]}
    source={require('./spinning_ball.png')}
/>

How would I stop this animation? For example, when navigating away to another screen or after a user clicks on a button.

I tried using this.state.angle.stopAnimation() but noticed run animation still being printed in the console. Is there a different stop method I should be calling to prevent the start callback from being executed?

解决方案

Based on my comment in Nguyên Hoàng's answer. Here is another way to stop the looping animation if you call this.state.angle.stopAnimation():

runAnimation() {
  this.state.angle.setValue(0);
  Animated.timing(this.state.angle, {
    toValue: 360,
    duration: 8000,
    easing: Easing.linear
  }).start((o) => {
    if(o.finished) {
      this.runAnimation();
    }
  });
}

这篇关于如何在React Native中停止循环动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆