You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Expo中Lottie动画初始加载时无法播放问题

解决Expo iPhone模拟器上Lottie首次挂载不自动播放的问题

问题分析

在Expo的iPhone模拟器环境中,Lottie动画的资源加载时机和组件挂载时机存在错位,导致首次挂载时autoPlay或手动调用play()无法触发;而热重载时资源已被缓存,动画就能正常循环播放。

可行解决方案

1. 监听动画加载完成回调触发播放

放弃依赖useEffect空依赖项,改用Lottie内置的onAnimationLoaded回调,确保资源完全加载后再执行播放:

import React from "react";
import LottieView from "lottie-react-native";
import { useRef } from "react";

function CarAnim(props) {
  const animationRef = useRef(null);

  const handleLoaded = () => {
    animationRef.current?.play();
  };

  return (
    <LottieView
      ref={animationRef}
      loop
      style={{ width: 200, height: 200 }}
      source={require("../assets/carAnimJs.json")}
      onAnimationLoaded={handleLoaded}
    />
  );
}

export default CarAnim;

这里移除了autoPlay属性,避免和手动播放逻辑冲突,确保动画只在资源就绪后启动。

2. 延迟调用播放方法

如果回调方式无效,可尝试给play()加微小延迟,让组件和资源完成初始化:

import React from "react";
import LottieView from "lottie-react-native";
import { useEffect, useRef } from "react";

function CarAnim(props) {
  const animationRef = useRef(null);

  useEffect(() => {
    const timer = setTimeout(() => {
      animationRef.current?.play();
    }, 100); // 可根据实际情况调整延迟时长
    
    return () => clearTimeout(timer);
  }, []);

  return (
    <LottieView
      ref={animationRef}
      loop
      style={{ width: 200, height: 200 }}
      source={require("../assets/carAnimJs.json")}
    />
  );
}

export default CarAnim;

3. 验证动画资源完整性

检查carAnimJs.json是否为标准Lottie格式,无文件损坏。可以用Lottie官方预览工具打开该文件,确认动画本身能正常播放,必要时重新导出动画资源。

4. 更新依赖版本

运行以下命令更新Expo和Lottie相关依赖,修复已知的兼容性问题:

expo upgrade
npm install lottie-react-native@latest

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 17:17:14