【问题标题】:How to re-play Lottie animation in React Native如何在 React Native 中重新播放 Lottie 动画
【发布时间】:2021-02-12 19:07:48
【问题描述】:

我正在尝试将“react-native-app-intro-slider”与 Lottie 动画一起使用。

效果很好,但是当我单击返回或下一步按钮时,动画停止播放。

如何重新播放动画?

提前致谢!

const renderItem = ({ item }) => {
  return (
    <View style={styles.container}> 
      <LottieView
        ref={LottieRef}
        autoPlay
        loop
        source={item.lottie}
      />
    </View>
  </ImageBackground>
)}

const slideChange = () => {
  LottieRef.current.play(); // it doesn't work
}

useEffect(() => {
  if (LottieRef.current !== null) {
    LottieRef.current.play(); // it doesn't work
  }
}, [LottieRef])

...

<AppIntroSlider 
   renderItem={renderItem} 
   data={slides} 
   onDone={onDone}
   onSlideChange={slideChange}
   showSkipButton
   showPrevButton
/>

【问题讨论】:

  • 我试图重新创建它,但是将循环和自动播放设置为 true,动画会按预期不断重复。 snack.expo.io/@nipuna777/app-intro-slider-with-lottie 是否需要进行其他更改?
  • @nipuna777 感谢您的回复。我想问的是,当我单击“返回”按钮(或向左滑动)时,动画并没有不断重复。使用我的设备(android),您的 Snack 中也会发生同样的事情(动画效果很好,但不适用于以前的滑块页面)
  • 嗯,这看起来像一个错误。我升级到最新版本并解决了 iOS 上的问题。但要在 Android 上修复它,我不得不在幻灯片更改时强制重新渲染。您可以查看更新后的零食,看看这是否适合您。
  • @nipuna777 哇,完美!非常感谢你是个天才!

标签: react-native lottie


【解决方案1】:

最近有同样的问题。如果您不想使用 ref 方法,您可以使用旧技巧在 LottieView 上设置 key 属性,该属性应该与源相关,因此当该源更改 key 属性时将收到一个新值,React 将重新渲染它,例如

<LottieView
    // other props you might need
    key={item.id}
    source={item.lottie}
/>

【讨论】:

    【解决方案2】:

    您需要将.play() 添加到componentDidMount 或useEffect 中,以便在每个组件挂载上播放动画。

    你可以做类似的事情

    import React from 'react';
    import LottieView from 'lottie-react-native';
     
    export default class BasicExample extends React.Component {
      componentDidMount() {
        this.animation.play();
        // Or set a specific startFrame and endFrame with:
        this.animation.play(30, 120);
      }
     
      render() {
        return (
          <LottieView
            ref={animation => {
              this.animation = animation;
            }}
            source={require('../path/to/animation.json')}
          />
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 2020-08-23
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      • 1970-01-01
      • 2022-10-02
      相关资源
      最近更新 更多