繁体   English   中英

如何在 onClick() 事件中使用 webAnimationsAPI?

[英]How can I use webAnimationsAPI in an onClick() event?

我正在尝试使用此代码在狗被点击时让狗跳,但我希望使用 animation 来让它感觉狗已经跳了。 相反,我收到此错误“错误:无效的挂钩调用。挂钩只能在 function 组件的主体内部调用”

 import React from "react"; import useWebAnimations from "@wellyshen/use-web-animations"; import "./App.css"; import Dog from "./images/dog.gif"; import Ball from "./images/ball.gif";

 function App() { const DogJump = () => { const dog = document.getElementById("dog"); useWebAnimations(dog, { keyframes: [ { transform: "translate(0, 0)" }, { transform: "translate(200, 0)" }, ], timing: { duration: 1000, direction: "alternate", }, }); }; return ( <div> <img ref={ref} className="ball" src={Ball} alt="ball" /> <img id="dog" className="dog" src={Dog} alt="dog" onClick={DogJump} /> </div> ); } export default App;

错误说明了一切,不能在事件处理程序中调用钩子,只能在 function 组件中调用(顶级函数)。 您可以检查hooks 的规则

我查看了图书馆提供的指南(其中之一在这里),并提出了以下工作示例 可能你需要稍微调整一下,但你明白了。 我必须指定translateXtranslateY才能使其正常工作,但不能使用translate速记(出现错误Failed to execute 'animate' on 'Element': Partial keyframes are not supported )。

顺便说一句,图书馆看起来很酷,我不知道。 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM