[英]React not re-rendering style changes with useState
我正在尝试使用按钮更新动画速度。 按下按钮时,没有任何变化,但切换选项卡时,它会更新为设置的速度。
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>
);
}
我刚刚测试了您的代码,速度本身确实发生了变化(如果您检查 HTML 节点本身,您将看到正确的时间)。
我相信它不起作用的原因是因为你的 CSS 动画设置为infinite
,所以理论上,动画仍在运行(alt-tabbing 可能会刷新动画,因为它在选项卡隐藏时没有运行)。
您可以通过设置新key
(强制重新创建 img 节点)在速度发生变化时重新创建 DOM 节点本身:
<img key={speed} src={logo} style={animationStyle} className="App-logo-circle" id='spinnerLogo'/>
但这会重置看起来参差不齐且不是最佳的动画。
我建议使用react-spring来微调动画。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.