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

在React组件渲染时如何禁用元素的初始动画效果

解决方案

问题根源

你给.button-background默认绑定了unToggle动画,组件首次渲染时浏览器会自动执行这段动画,就出现了页面加载时的自动动效。

修改步骤

  • 新增一个交互状态标记,初始值为false,用户首次点击开关后才设为true
  • 调整样式规则:初始状态直接设置元素定位值,不绑定动画,仅在已交互的状态下才启用动画效果

完整修改后代码

import { useState } from "react";
import styled, { keyframes } from "styled-components";

const toggle = keyframes`
      from {
        transform: translate(0);
      }
      to {
        transform: translate(149px);
      }`;
const unToggle = keyframes`
      from {
        transform: translate(149px);
      }
      to {
        transform: translate(0);
      }`;

const ButtonStyles = styled.div`
  margin-top: 1rem;
  width: 300px;
  height: 50px;
  background-color: #fff;
  border-radius: 50px;
  padding: 3px;
  cursor: pointer;

  .button-container {
    display: flex;
    height: inherit;
    width: inherit;
    align-items: center;

    .button-background {
      width: 150px;
      height: inherit;
      background-color: blue;
      border-radius: 50px;
      /* 初始状态直接设定位,无动画 */
      transform: translate(0);
      /* 仅已交互后才启用动画 */
      &.animating {
        animation: 0.6s ease-in-out ${unToggle};
        animation-fill-mode: forwards;
        &.active {
          animation: 0.6s ease-in-out ${toggle};
          animation-fill-mode: forwards;
        }
      }
    }

    .button-country {
      width: inherit;
      position: absolute;
      display: flex;
      justify-content: space-around;
      color: #979797;
      span:nth-child(1) {
        color: #fff;
      }
      /* 仅已交互后才启用过渡效果,避免初始闪动 */
      &.animating {
        transition: 1.2s;
        span:nth-child(1) {
          transition: 1.2s;
        }
        &.white {
          transition: 1.2s;
          color: #fff;
          span:nth-child(1) {
            color: #979797;
          }
        }
      }
    }
  }
`;

export default function Button() {
  const [toggleButton, setToggleButton] = useState("");
  const [labelColor, setLabelColor] = useState("");
  // 控制是否启用动画的状态标记
  const [hasInteracted, setHasInteracted] = useState(false);

  return (
    <ButtonStyles>
      <div
        onClick={() => {
          // 首次点击后标记为已交互,启用所有动画和过渡
          if (!hasInteracted) setHasInteracted(true);
          setToggleButton(!toggleButton ? "active" : "");
          setLabelColor(!labelColor ? "white" : "");
        }}
        className="button-container"
      >
        <div className={`button-background ${hasInteracted ? 'animating' : ''} ${toggleButton}`}></div>
        <div className={`button-country ${hasInteracted ? 'animating' : ''} ${labelColor}`}>
          <span>Brasil</span>
          <span>EUA</span>
        </div>
      </div>
    </ButtonStyles>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:18:02