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

React项目中lottie-player重复注册引发DOMException问题咨询

问题分析与解决方案

错误成因

这个错误的核心原因是:浏览器的CustomElementRegistry中,lottie-player这个自定义元素名称已经被注册过,无法重复执行注册操作。

你的代码问题

你在项目多处使用的代码里,每次都会加载<script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>这个脚本。而这个脚本的核心逻辑就是向浏览器注册lottie-player自定义元素——当你在多个组件或页面重复加载这个脚本时,就会多次触发自定义元素的注册操作,从而抛出这个重复注册的异常。

解决办法

1. 统一引入脚本(最直接)

把加载lottie-player.js的<script>标签只放在项目的入口文件里(比如public/index.html的<body>末尾),确保整个项目只会加载一次这个脚本。之后在任何组件里直接使用<lottie-player>标签即可,不需要重复引入脚本。

2. 使用React专用的Lottie库(更符合React生态)

放弃直接使用原生自定义元素的方式,改用React封装的Lottie库,比如lottie-react:

  • 安装依赖:npm install lottie-react
  • 在组件中使用示例:
import Lottie from "lottie-react";
import animationData from "./path/to/your/animation.json";

function LottieAnimation() {
  return <Lottie animationData={animationData} loop autoplay style={{width: 300, height: 300}} />;
}

这种方式不需要手动引入脚本,也不会出现重复注册的问题,更适配React的组件生命周期。

3. 组件内条件加载脚本(临时方案)

如果必须在组件内引入脚本,可以先检查lottie-player是否已注册,再决定是否加载:

import { useEffect } from 'react';

function LottiePlayerComponent() {
  useEffect(() => {
    // 检查自定义元素是否已注册
    if (!customElements.get('lottie-player')) {
      const script = document.createElement('script');
      script.src = 'https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js';
      script.async = true;
      document.body.appendChild(script);
    }
  }, []);

  return (
    <lottie-player 
      src="https://assets4.lottiefiles.com/packages/lf20_pJo4Hp.json"  
      background="transparent"  
      speed="1"  
      style={{width: '300px', height: '300px'}}  
      loop controls autoplay
    ></lottie-player>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:15:58