所以我有4个组件,它们都在onClick处理程序中做同样的事情。
我必须在它们中的每一个中定义这个代码。
我不知道如何使其可重用的原因是,您不能在常规的非react实用函数中调用setUserContext。我试着创建一个钩子,但是你不能在onClick中使用钩子作为回调函数。
我在这里有什么选择?
const { userContext, setUserContext } = useContext(UserContext);
// this goes inside onClick and is defined in like 4 components (too much repetition)
const favoriteItem = (e) => {
e.stopPropagation();
e.preventDefault();
setUserContext({ ...userContext, favoriteItems: JSON.parse(localStorage.getItem("favoriteItems")) });
}
发布于 2021-09-25 20:02:07
您可以创建自定义挂钩。
const useCustomHook = () => {
const { userContext, setUserContext } = useContext(UserContext);
const favoriteItem = (event, game) => {
e.stopPropagation();
e.preventDefault();
setUserContext({ ...userContext, favoriteItems: JSON.parse(localStorage.getItem("favoriteItems")) });
}
return { favoriteItem }
}
export default useCustomHook;
您的组件可以做到这一点。
...
const { favoriteItem } = useCustomHook()
return (
<Element onClick={(event) => favoriteItem(event, game)} />
)
...
https://stackoverflow.com/questions/69331745
复制