React Native Lottie查看动画播放/暂停问题

时间:2018-04-04 21:23:07

标签: animation react-native lottie

我正在使用React Native Lottie Wrapper在屏幕上显示动画 我需要一个功能来播放/暂停/恢复动画。

以下是我的代码的一部分:

...

constructor(props) {
  super(props);
  this.state = {
    progress: new Animated.Value(0)
  };
}

static navigationOptions = {
  title: "Details",
  headerStyle: {
    backgroundColor: '#f4511e',
  },
  headerTintColor: '#fff',
  headerTitleStyle: {
    fontWeight: 'bold',
  },
  headerTruncatedBackTitle: 'List'
};

componentDidMount() {
  this.animation.play();
}

playLottie() {
 console.log('play');
}

pauseLottie() {
  console.log('pause');
}

render() {
  return (
    <View>
      <Animation
        ref={animation => { this.animation = animation; }}
        source={require('../../../../assets/anim/balloons.json')}
        style={{height: 300, width: '100%'}}
        loop={false}
        progress={this.state.progress}
      />
      <Text>Course with id: {this.props.navigation.state.params.courseId}</Text>
        <Button 
          onPress={this.playLottie}
          title="Play Lottie"
          color="#841584"
          accessibilityLabel="Play video"
        />
        <Button 
          onPress={this.pauseLottie}
          title="Pause Lottie"
          color="#841584"
          accessibilityLabel="Pause video"
        />
     </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

...

动画播放效果不错,但我无法暂停并恢复播放 有没有人有这个问题的解决方案?

P.S。我曾尝试在 pauseLottie()方法中使用 this.animation ,但它表示未定义。

提前谢谢!

3 个答案:

答案 0 :(得分:1)

您必须从播放/暂停功能设置状态。要访问Component的状态,必须将该函数绑定到组件类:

构造函数中的第一个选项:

constructor(props) {
  super(props);
  this.playLottie.bind(this);
  this.pauseLottie.bind(this);
}
声明内部类时使用es6函数语法的

或第二个选项:

playLottie = () => {
 ...
}

pauseLottie = () => {
 ...
}

在这些函数调用setState中,添加要设置的值。在你的情况下,我会:

playLottie = () => {
  this.setState({ progress: true })
}

pauseLottie = () => {
  this.setState({ progress: false })
}

将这两个函数绑定到类组件非常重要,因为您将无法访问组件道具。这就是为什么它会给你一个错误setState is not a function

你的渲染效果很好;)

答案 1 :(得分:0)

@parohy给了我一个主意,所以我尝试了这样的事情:

constructor(props) {
  super(props);
  this.playLottie.bind(this);
  this.pauseLottie.bind(this);
  this.state = {
    progress: new Animated.Value(0)
  };
}

playLottie = () => {
  Animated.timing(this.state.progress, {
    toValue: 1,
    duration: 10000,
  }).start();
}

pauseLottie = () => {
  this.state.progress.stopAnimation(this.realProgress);
}

realProgress = (value) => {
  console.log(value);
};
...

对我来说,它的工作正常!播放和暂停选项按预期工作。

答案 2 :(得分:0)

您可以通过更改speed道具来暂停和播放Lottie动画,其中speed={0}将LottieView组件置于暂停状态,speed={1}以正常速度播放。

这里是一个例子:

playAnimation = () => {
    this.setState({speed: 1})
}

pauseAnimation = () => {
    this.setState({speed: 0})
}

<LottieView
    source={this.state.sourceAnimation}
    speed={this.state.speed} />
相关问题