首页 > 解决方案 > 如何在 React Native 中立即停止循环动画

问题描述

我正在尝试在本机反应中实现循环动画。我也可以停止动画,但只有在完成正在运行的动画后才会停止。有没有办法立即阻止它。由于我正在改变statevalue ,我认为我不能使用Animated.loop.

编辑:我尝试使用停止动画

Animated.timing(this.state.opacity).stop()

但这对动画没有影响,它只是继续。所以我添加了一个布尔值来控制它,它有效,但只有在完成正在进行的动画循环之后。

这是我的代码

this.state = {
   varyingText: 'location',
   stopAnimation: false,
   opacity: new Animated.Value(0),
};


componentDidMount = () => {
    this.startAnimation();
  };

  startAnimation = () => {
    if (this.state.stopAnimation) return;

    Animated.timing(this.state.opacity, {
      toValue: 1,
      duration: 1000
    }).start(() => {
      Animated.timing(this.state.opacity, {
        toValue: 0,
        duration: 1000
      }).start(() => {
        this.setState({
          varyingText: 'location 1',
        }, () => {
          Animated.timing(this.state.opacity, {
            toValue: 1,
            duration: 1000
          }).start(() => {
            Animated.timing(this.state.opacity, {
              toValue: 0,
              duration: 1000
            }).start(() => {
              this.setState({
                varyingText: 'location 2',
              }, () => {
                Animated.timing(this.state.opacity, {
                  toValue: 1,
                  duration: 1000
                }).start(() => {
                  Animated.timing(this.state.opacity, {
                    toValue: 0,
                    duration: 1000
                  }).start(() => {
                    this.setState({
                      varyingText: 'location 3',
                    }, () => this.startAnimation())
                  })
                })
              })
            })
          })
        })
      })
    });
  };

stopAnimation = () => {
    this.setState({
      stopAnimation: true,
    });
  };

render() {
    const opacityStyle = {
      opacity: this.state.opacity,
    };
    return (
      <View style={styles.view}>
          <Animated.Text style={...opacityStyle}>
             {this.state.varyingText}
          </Animated.Text>

          <Button
             onPress={this.stopAnimation}
             title="Stop"
             color="#841584"
          />
      </View>
    );
  }

在代码中,如果我在 text 为 时停止动画location 1,它会在显示后停止location 2

标签: react-native

解决方案


推荐阅读