英文:
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(() => {
return backgroundColor;
}, []);
const buttonStyle: React.CSSProperties = {
background: background,
};
return (
<button style={buttonStyle}>
)
答案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(() => {
return newBackgroundColor(); // some random color
}, [newBackgroundColor]);
const buttonStyle: React.CSSProperties = {
background: background,
};
return (
<button style={buttonStyle}>
)
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论