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

使用@lottiefiles/react-lottie-player时lottieRef为何仅返回null?

解决@lottiefiles/react-lottie-player中lottieRef获取为null的问题

我在使用@lottiefiles/react-lottie-player库时,需要获取lottieRef来与动画交互,但始终得到null值。还有一个奇怪现象:打印lottie对象时,能看到内部有内容但表面显示为null;直接打印lottie.current则返回null。

问题代码

import React, { useEffect, useRef } from "react";
import { Player } from "@lottiefiles/react-lottie-player";

export default function App() {
  const player = useRef(null);
  const lottie = useRef(null);

  useEffect(() => {
    if (lottie && lottie.current) {
      console.log(lottie.current); // 返回null
    }
  }, []);

  return (
    <div className="App">
      <Player
        lottieRef={(data) => (lottie.current = data)}
        ref={player}
        onEvent={(event) => {
          if (event === "load") {
            lottie.current.play(); // 无任何反应
          }
        }}
        keepLastFrame={true}
        autoplay={false}
        loop={true}
        src="https://lottie.host/2c01fd6c-437d-494e-af27-2a37e322bc60/prXv4Ic6px.json"
        style={{ width: "100%", height: "2.5em", padding: "0", margin: "0" }}
      />
    </div>
  );
}

问题原因

  1. useEffect执行时机不对:空依赖的useEffect在组件挂载后立即执行,此时Lottie动画还未加载完成,lottieRef的回调尚未触发,所以lottie.current仍是null。
  2. onEvent事件判断错误:该库的onEvent参数并非字符串,而是包含eventName属性的对象,直接判断event === "load"永远不会成立,导致play()调用无效。

修复方案

方案1:正确监听load事件

修改onEvent的判断逻辑,通过event.eventName识别事件类型:

onEvent={(event) => {
  if (event.eventName === "load") {
    lottie.current?.play();
  }
}}

方案2:在lottieRef回调中直接操作

无需额外的useEffect,在lottieRef的回调函数里直接获取实例并执行操作:

lottieRef={(data) => {
  lottie.current = data;
  // 动画加载完成后立即执行播放
  data.play();
}}

方案3:监听player实例变化触发useEffect

如果需要在useEffect中处理逻辑,可以将player.current作为依赖,当player实例更新时触发:

useEffect(() => {
  if (lottie.current) {
    console.log(lottie.current);
    lottie.current.play();
  }
}, [player.current]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 04:20:27