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

React项目中使用react-lottie展示多个不同Lottie动画问题咨询

问题原因

你的两个Lottie组件都复用了同一个defaultOptions配置对象,该对象内的animationData属性固定绑定为svg1,所以两个组件都会渲染同一个svg1动画。

解决方案

你可以把公共的通用配置抽离,针对不同动画传入对应的animationData生成独立配置,还可以做进一步封装方便后续新增更多动画:

import React from 'react';
import Lottie from 'react-lottie';
import svg1 from '../../assets/svg/svg1';
import svg2 from '../../assets/svg/svg2';

// 抽离公共的通用配置
const commonOptions = {
  loop: true,
  autoplay: true,
  rendererSettings: {
    preserveAspectRatio: 'xMidYMid slice',
  },
};

// 封装生成Lottie配置的函数,后续新增动画只需要传入对应的svg资源即可
const getLottieOptions = (animationData) => {
  return {
    ...commonOptions,
    animationData
  }
}

// 也可以进一步封装成自定义Lottie组件,复用更方便
const CustomLottie = ({animationData, height=900, width=900}) => {
  return <Lottie options={getLottieOptions(animationData)} height={height} width={width} />
}

export default function Landing() {
    return (
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
            <h1>Landing Page</h1>
            <CustomLottie animationData={svg1} />
            <CustomLottie animationData={svg2} />
            {/* 后续新增动画只需要加一行,传入对应的svg资源即可 */}
            {/* <CustomLottie animationData={svg3} /> */}
        </div>
    );
}

修改后两个Lottie就会分别渲染svg1和svg2的动画,后续新增动画也不需要重复写配置,直接传入新的svg资源即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:15:07