【问题标题】:React not re-rendering style changes with useState使用 useState 响应不重新渲染样式更改
【发布时间】:2020-06-25 23:58:11
【问题描述】:

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

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>
  );
}

【问题讨论】:

    标签: javascript html reactjs


    【解决方案1】:

    我刚刚测试了您的代码,速度本身确实发生了变化(如果您检查 HTML 节点本身,您会看到正确的时间)。

    我相信它不起作用的原因是因为您的CSS动画设置为infinite,所以在理论上,动画仍在运行(Alt-Tabbing可能会刷新动画,因为当标签时不在运行时刷新动画隐藏)。

    当速度发生变化时,您可以通过设置新的key(强制重新创建 img 节点)重新创建 DOM 节点:

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

    但这会重置看起来参差不齐且不是最佳的动画。

    我建议使用react-spring,它可以让您微调动画。

    【讨论】:

      猜你喜欢
      • 2020-06-13
      • 2022-01-04
      • 2020-01-13
      • 1970-01-01
      • 1970-01-01
      • 2021-03-24
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      相关资源
      最近更新 更多