无法使用 useMemo 阻止颜色背景的重新渲染吗?

huangapple go评论69阅读模式
英文:

Can't stop re-render for color background with useMemo React?

问题

在每次重新渲染时,它生成一个新的颜色。如何缓存第一次初始化的颜色并在以后重复使用它?

const backgroundColor = newBackgroundColor(); // 一些随机颜色

const background = React.useMemo(() => {
  return backgroundColor;
}, []);

const buttonStyle: React.CSSProperties = {
  background: background,
};

return (
  <button style={buttonStyle}>
)
英文:

On each re-render it generates a new color. How do I cache the first color it gets initialized and re-use it each now?

  const backgroundColor = newBackgroundColor(); // some random color

  const background = React.useMemo(() =&gt; {
    return backgroundColor;
  }, []);

  const buttonStyle: React.CSSProperties = {
          background: background,
  };

  return (
    &lt;button style={buttonStyle}&gt;
  )

答案1

得分: 4

  const background = React.useMemo(() => {
    return newBackgroundColor(); // some random color
  }, [newBackgroundColor]);

  const buttonStyle: React.CSSProperties = {
          background: background,
  };

  return (
    <button style={buttonStyle}>
  )
英文:
  const background = React.useMemo(() =&gt; {
    return newBackgroundColor(); // some random color
  }, [newBackgroundColor]);

  const buttonStyle: React.CSSProperties = {
          background: background,
  };

  return (
    &lt;button style={buttonStyle}&gt;
  )


</details>



huangapple
  • 本文由 发表于 2023年3月9日 15:32:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681592.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定