首页 > 解决方案 > 如何在 React 中每次点击时运行动画?

问题描述

我想要一个每次点击都会运行的动画。

但是,它仅在第一次运行,而不是在第二次单击后运行。

有办法吗?

  const inputEl = useRef();
  const onButtonClick = () => {
    inputEl.current.style.animation = "0.7s ease-in-out 0s 1 testKeyword";
  };
return(
   <input ref={inputEl} type="text" />
   <button onClick={onButtonClick}>Focus the input</button>
);
@keyframes testKeyword {
  0% {
    opacity: 0;
    transform: scale(1);
  }
  50% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

标签: javascriptcssreactjsanimation

解决方案


根据您的需要,我有 2 种不同的解决方案:

解决方案1:使用useRef

js文件

const inputEl = useRef();

const handleButtonClick = () => {
    inputEl.current.style.animation = "0.7s ease-in-out 0s 1 testKeyword";
}

const handleAnimationEnd = () => {
    inputEl.current.style.animation = "none";
}
<input ref={inputEl} onAnimationEnd={handleAnimationEnd} type="text"/>

<button onClick={handleButtonClick} >Focus the input</button>  

css 文件:

@keyframes testKeyword {
  0% {
    opacity: 0;
    transform: scale(1);
  }
  50% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

解决方案2:使用useState

.js 文件:

const [clicked, setClicked] = useState(false);

<input type="text" class={clicked === true ? "animate" : null} onAnimationEnd={() => setClicked(false)}/>

<button onClick={() => setClicked(true)}>Focus the input</button>

css 文件:

.animate {
  animation: 0.7s ease-in-out 0s 1 testKeyword;
}

@keyframes testKeyword {
  0% {
    opacity: 0;
    transform: scale(1);
  }
  50% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

推荐阅读