You need to enable JavaScript to run this app. React Native中使用react-native-app-intro-slider时如何重放Lottie动画?
优惠活动
大模型
产品
解决方案
定价
更多

React Native中使用react-native-app-intro-slider时如何重放Lottie动画?

React Native 引导页切换时Lottie动画重播实现

原有代码失效的核心原因

  • 全局共用单个LottieRef:AppIntroSlider默认只渲染当前激活页的组件,切换幻灯片时旧页的LottieView实例会被卸载,全局共享的ref会指向已经销毁的旧实例,调用play方法自然没有任何反应。
  • 直接调用play不重置进度:哪怕拿到了正确的Lottie实例,如果动画已经播放到结束帧,直接调用play不会自动从头开始,必须先把进度重置到起始位置。

可落地的实现方案

方案1:通过重挂载触发自动播放(优先推荐,稳定性最高)

不需要单独维护ref,利用LottieView重挂载时会自动根据autoPlay属性从头播放的特性实现效果:

  1. 新增状态存储当前激活的幻灯片索引,联动Lottie的渲染逻辑
const [activeSlideIndex, setActiveSlideIndex] = useState(0);
  1. 改造renderItem方法,给LottieView增加绑定激活状态的key,key变化时会触发组件销毁重建,自动从头播放动画
const renderItem = ({ item }) => {
  return (
    <View style={styles.container}> 
      <LottieView
        key={`lottie-${item.id}-${activeSlideIndex === item.id}`}
        autoPlay
        loop
        source={item.lottie}
      />
    </View>
  )
}
  1. 替换原来的切换回调,把当前索引同步到状态中
const handleSlideChange = (index) => {
  setActiveSlideIndex(index);
}
  1. 将AppIntroSlider的onSlideChange绑定到新的回调上即可
<AppIntroSlider 
   renderItem={renderItem} 
   data={slides} 
   onDone={onDone}
   onSlideChange={handleSlideChange}
   showSkipButton
   showPrevButton
/>

这个方案完全绕开ref指向错误的问题,适配Lottie组件的版本变动能力更强。

方案2:为每个幻灯片独立维护Lottie实例

如果需要更精细控制动画进度,就不能全局共用一个ref,要给每一页的Lottie单独存储实例:

  1. 初始化一个ref集合,用来存所有页面的Lottie实例
const lottieInstanceMap = useRef({});
  1. 改造renderItem,给每个LottieView绑定单独的ref,存到集合中
const renderItem = ({ item }) => {
  return (
    <View style={styles.container}> 
      <LottieView
        ref={(ref) => {
          lottieInstanceMap.current[item.id] = ref
        }}
        autoPlay
        loop
        source={item.lottie}
      />
    </View>
  )
}
  1. 改造切换回调,找到当前页对应的Lottie实例,先重置进度再触发播放
const handleSlideChange = (index) => {
  const currentSlide = slides[index];
  const currentLottie = lottieInstanceMap.current[currentSlide.id];
  currentLottie?.reset();
  currentLottie?.play();
}

注意:一定要先调用reset()再调用play(),否则如果动画已经循环到末尾,直接触发play不会从头开始,会直接停在结束位置。


内容的提问来源于stack exchange,提问作者leesinmaster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.04 11:06:09