javascript - 如何在 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;
}
}
解决方案
根据您的需要,我有 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;
}
}
推荐阅读
- python-3.x - 子进程的输出以附加列表
- php - PHP服务器创建带有header()的图像不显示
- ruby - Google Protobuf 未定义方法 msgclass' 用于 nil:NilClass
- javascript - React-Native 可见性过滤器不起作用?
- javascript - ajax调用后Jquery Event绑定两次
- kubernetes - 错误:未能发现支持的资源 Kubernetes 谷歌云平台
- reactjs - 如何在 ReactJS 中为子路由概念创建默认路由
- sql - 在 MemSQL 中对 1+ 亿行查询 GROUP BY
- flask - Python/Flask:为什么程序接收的是 GET 请求而不是 POST 请求?
- web-services - SOAP 和 HTTP 响应代码