Javascript 使用useState对样式更改作出反应而不重新渲染

Javascript 使用useState对样式更改作出反应而不重新渲染,javascript,html,reactjs,Javascript,Html,Reactjs,我正在尝试用按钮更新动画速度。按下按钮时,没有任何变化,但切换选项卡时,它会更新到设定的速度 function Homepg() { const [speed, setSpeed] = useState(15); function faster () { setSpeed(speed === 1 ? speed : speed-2) }; function slower() { setSpeed(speed+2); } const animatio

我正在尝试用按钮更新动画速度。按下按钮时,没有任何变化,但切换选项卡时,它会更新到设定的速度

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>
  );
}
函数Homepg(){
常数[速度,设定速度]=使用状态(15);
功能更快(){
设置速度(速度===1?速度:速度-2)
};
函数(){
设定速度(速度+2);
}
常量动画样式={
动画:`App logo spin infinite${speed}s linear`
}
返回(
您好,欢迎来到Swiss Plus网站的开始。希望您在这里过得愉快。

增加旋转速度! 降低旋转速度! ); }
我刚刚测试了您的代码,速度本身确实发生了变化(如果您检查HTML节点本身,您将看到正确的时间)

我认为它不起作用的原因是因为CSS动画设置为无限,因此理论上,动画仍在运行(alt tabbing可能会刷新动画,因为当选项卡隐藏时动画不运行)

通过设置新的
(强制重新创建img节点),可以在速度改变时重新创建DOM节点本身:


但这将重置动画,这将看起来锯齿状,不是最佳的

我建议您使用它来微调动画

<img key={speed} src={logo} style={animationStyle} className="App-logo-circle" id='spinnerLogo'/>