循环播放React Native动画动画

4
我正在尝试将以下动画循环无限次,直到发生特定状态:
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>
        );
    }
}

这里的一切都很顺利,动画完成一次(因为我没有在任何地方循环)。

我如何让我的 Animated.Image 循环直到我达到特定状态?我只想要无限循环,并在准备好时停止动画或开始另一个动画。

3个回答

12

将你的动画存储在一个变量中以便访问,并使用 Animated.loop() 将你的动画包裹起来。然后,你可以随意使用存储动画的变量上的 .start().stop() 方法。

因此,像下面这样做:

this.springAnimation = Animated.loop(
  Animated.spring(
    this.springValue,
    {
      toValue: 1,
      friction: 1,
      tension: 1,
      duration:5000
    }
  ).start()
)

您可以在此处找到更多相关信息:

https://facebook.github.io/react-native/docs/animated.html#loop


这绝对应该被选为正确答案。 - Brandon.Blanchard

3

将回调函数传递给start函数以检查是否重新启动动画。可以将其分解为以下内容:

    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);
      }  

也许值得考虑一下,传递给.start方法的回调函数接受一个对象,如下所示:{ finished: Boolean },它允许您确保下一次调用animate时不会有任何动画正在进行或已安排或其他什么情况,同时它还允许您在任何时候停止动画,因为调用AnimatedValue.stopAnimation()方法将把o.finished更改为false,从而不重新启动动画(当然只有在需要控制它时才这样做(:) - MaieonBrix

-3
你可以使用 setInterval 来保持动画播放,并在需要时删除间隔。我会这样做:
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)
...

1
setInterval可能会存在意外延迟,这些延迟会在动画循环中对用户产生影响。 - Mark Entingh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接