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

React实现点击按钮切换Lottie动画资源的方法咨询

React点击切换Lottie动画实现方案

操作步骤

  • 第一步:安装Lottie适配React的依赖库
    执行以下命令完成安装:
    npm install lottie-react
    如果使用yarn则执行:
    yarn add lottie-react
  • 第二步:准备动画资源
    将你需要用到的两个Lottie动画json文件存入项目目录,推荐放在src/assets/lotties/路径下,分别命名为garside-work.json和oak-work.json。
  • 第三步:修改原有代码,替换图片逻辑为Lottie逻辑
    以下是修改后的完整代码:
import React, { useState } from "react"
import styled from "styled-components"
import Lottie from "lottie-react"
import PurchaseButton from "../buttons/PurchaseButton"
import { themes } from "../styles/ColorStyles"
import { H1, MediumText } from "../styles/TextStyles"
// 引入两个Lottie动画资源
import GarsideAnimation from "../assets/lotties/garside-work.json"
import OakAnimation from "../assets/lotties/oak-work.json"

const Worksites = {
  Garside: {
    animation: GarsideAnimation,
  },
  OakandOcean: {
    animation: OakAnimation,
  },
}

export default function GallerySection() {
  const [selectedWorksites, setSelectedWorksites] = useState(Worksites.Garside)

  return (
    <Wrapper>
      <ContentWrapper>
        <TextWrapper>
          <Lockup>
            <Title>See how trades work in GoTradie</Title>
          </Lockup>
          <Description>
            You don’t have to believe us checkout some of the tradies already
            using Gotradie
          </Description>
          <ul>
            <ButtonGroup>
              <PurchaseButton
                title="Garside Electrcial & Solar"
                className={`${
                  selectedWorksites === Worksites.Garside ? "active" : "static"
                }`}
                onClick={() => setSelectedWorksites(Worksites.Garside)}
              />

              <PurchaseButton
                title="Oak & Ocean Building"
                className={`${
                  selectedWorksites === Worksites.OakandOcean
                    ? "active"
                    : "static"
                }`}
                onClick={() => setSelectedWorksites(Worksites.OakandOcean)}
              />
            </ButtonGroup>
          </ul>
        </TextWrapper>
      </ContentWrapper>
      <ImageWrapper>
        {selectedWorksites ? (
          <div>
            {/* 替换img标签为Lottie组件,可自定义播放属性 */}
            <Lottie 
              animationData={selectedWorksites.animation} 
              loop={true}
              autoplay={true}
              style={{ width: "100%", height: "100%" }}
            />
          </div>
        ) : null}
      </ImageWrapper>
    </Wrapper>
  )
}

可选配置说明

你可以根据需求调整Lottie组件的属性:

  • loop:设置为true则动画循环播放,false则只播放一次
  • autoplay:设置为true则动画加载完成后自动播放
  • speed:传入数字控制播放速度,比如speed={2}就是2倍速播放
  • 也可以通过style或者className自定义动画容器的宽高、位置等样式

内容的提问来源于stack exchange,提问作者Anchor-Point

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 21:00:01