css 关键帧在 React 中无法正常工作

css keyframes donot work Properly In React

Hi everyone when i call css keyframes from my styles.css to index.js it dosenot work properly

这是我的 index.js 文件

    import React from 'react';
    import ReactDOM from 'react-dom';
    import { useState } from 'react';
    import "./Style.css";

    const BgChangeMouseEvent = () => {
      const [isEnterMouse, setIsEnterMouse] = useState(false);

      const handleBackground = state => {
        setIsEnterMouse(state);
      };

      return (
        <div
          className={isEnterMouse ? "logo" : ""}
          onMouseEnter={() => handleBackground(true)}
          onMouseLeave={() => handleBackground(true)}
        >
           <img alt='icon' src={"http://pngimg.com/uploads/car_logo/car_logo_PNG1644.png"}/>
        </div>

      );
    };

    ReactDOM.render(<BgChangeMouseEvent />, document.getElementById('root'));

这是我的 styles.css 文件


    .logo {
      left: -620px;
      top: -440px;

    }
    .logo {
      width: 100px;
      position: relative;
      animation-name: example;
      animation-duration: 6s;
    }
    @keyframes example {
      0%   { left:0px; top:0px; width:3000px}
      25%  { left:400px; top:200px;}
      100% { left:-620px; top:-440px;}
    }


I want to use css @keyframes for logo with mouse event but the logo dosenot change properly.

让我们看看,首先,监听器应该在图像上而不是 div 上,其次,当鼠标悬停在图像上时,触发动画的 class 也应该应用在图像上Image.Lastly,当鼠标不再位于图像上时,您想要将图像宽度更改回原始宽度,因此 isEnterMouse 应设置为 false i.e handleBackground(false)

(为了更好地查看徽标,我做了一些更改,如果您愿意,可以将其更改回来)

 <img
      alt="icon"
      onMouseEnter={() => handleBackground(true)}
      onMouseLeave={() => handleBackground(false)}
      className={`LogoImage ${
        isEnterMouse ? "LogoImageIncrease" : "LogoImageDecrease"
      }`}
      src={"http://pngimg.com/uploads/car_logo/car_logo_PNG1644.png"}
    />

Style.css

.LogoImage {
  width: 100px;
  height: 100px;
}
.logo {
  width: 100px;
  position: relative;
  animation-name: example;
  animation-duration: 6s;
}
.LogoImageIncrease {
  position: relative;
  animation: IncreaseWidth;
  animation-duration: 2s;
  animation-iteration-count: 1;
  animation-fill-mode: forwards;
}

@keyframes IncreaseWidth {
  0% {
    width: 100px;
  }
  100% {
    width: 200px;
  }
}

.LogoImageDecrease {
  position: relative;
  animation: DecreaseWidth;
  animation-duration: 2s;
  animation-iteration-count: 1;
  animation-fill-mode: forwards;
}

@keyframes DecreaseWidth {
  0% {
    width: 200px;
  }
  100% {
    width: 100px;
  }
}

CodeSandbox here