我正在尝试用一个按钮更新动画速度。当按钮被按下时,不会发生任何变化,但当标签被切换时,它会更新为设定的速度。
function Homepg() {
const [speed, setSpeed] = useState(15);
function faster () {
setSpeed(speed === 1 ? speed : speed-2)
};
function slower() {
setSpeed(speed+2);
}
const animationStyle = {
animation: `App-logo-spin infinite ${speed}s linear`
}
return (
<div className="App">
<header className="App-header">
<img src={logo} style={animationStyle} className="App-logo-circle" alt="White cross, with a blue bacground spining" id='spinnerLogo'/>
<p>Hello, and welcome to the begining of the Swiss Plus Website. <strong>We hope you enjoy your stay</strong></p>
<button className='App-button' id='fastLogoButton' onClick={faster}>Increase Spin Speed!</button>
<button className='App-button' id='slowLogoButton' onClick={slower}>Decrease Spin Speed!</button>
</header>
</div>
);
}发布于 2020-03-14 11:48:30
我刚刚测试了您的代码,速度本身确实发生了变化(如果您检查HTML节点本身,您将看到正确的时间)。
我相信它不起作用的原因是因为你的CSS动画设置为infinite,所以理论上,动画仍然在运行(alt- tab键可能会刷新动画,因为当标签隐藏时,它不会运行)。
当速度改变时,您可以通过设置新的key来重新创建DOM节点本身(强制重新创建img节点):
<img key={speed} src={logo} style={animationStyle} className="App-logo-circle" id='spinnerLogo'/> 但这将重置动画,这将看起来参差不齐,并不是最优的。
我建议使用react-spring,它允许你微调动画。
https://stackoverflow.com/questions/60679428
复制相似问题