据我了解,您使用 useCallback 来防止重新渲染,因此我一直在每个函数中使用它,而我的蜘蛛感觉告诉我这听起来已经很糟糕了。
但故事并没有就此结束,因为我一直在到处使用它,所以我现在将依赖项传递给我的所有子组件,他们不需要担心,如下例所示:
编辑//沙盒: https://codesandbox.io/s/bold-noether-0wdnp?file =/src/App.js
父组件(需要 colorButtons 和 currentColor)
const ColorPicker = ({onChange}) => {
const [currentColor, setCurrentColor] = useState({r: 255, g:0, b: 0})
const [colorButtons, setColorButtons] = useState({0: null})
const handleColorButtons = useCallback((isToggled, id) => {
/* code that uses colorButtons and currentColor */
}, [colorButtons, currentColor])
return <div className="color-picker">
<RgbColorPicker color={currentColor} onChange={setCurrentColor} />
<div className="color-buttons">
{
Object.entries(colorButtons).map(button => <ColorButton
//...
currentColor={currentColor}
onClick={handleColorButtons}
colorButtons={colorButtons}
/>)
}
</div>
</div>
}
Run Code Online (Sandbox Code Playgroud)
第一个子级(需要 style 和 currentColor,但从其父级免费获取 colorButtons)
const ColorButton = …Run Code Online (Sandbox Code Playgroud)