我有一段代码:
我的定制钩:
export const useSidebar = () => {
const [showSidebar, setShowSidebar] = useState(false);
const toggleSidebar = useCallback(() => {
setShowSidebar(!showSidebar);
}, [showSidebar]);
return [showSidebar, toggleSidebar] as const;
};我的边栏:
export const Sidebar = () => {
const [showSidebar, toggleSidebar] = useSidebar();
return (
<aside
className={`top-0 right-0 w-[35vw] bg-blue-600 p-10 pl-20 text-white fixed h-full ease-in-out duration-300 z-panel ${
showSidebar ? 'translate-x-0 ' : 'translate-x-full'
}`}
>
<button
className="flex text-4xl text-white items-center cursor-pointer fixed right-10 top-6 z-50"
onClick={() => toggleSidebar()}
>
x
</button>
<h3 className="mt-20 text-4xl font-semibold text-white">I am a sidebar</h3>
</aside>
);
};当我从钩子上调用toggleSidebar()时,我的侧边栏就不会出现。调试器指示showSidebar始终是false。
你能指出我做错了什么吗?
非常感谢。
发布于 2022-05-29 21:14:27
好的,我的错误我不能用钩子来做,所以我用了一个上下文。
export type SidebarContextType = {
isVisible: boolean;
toggleSidebar: () => void;
};
export const SidebarContext = createContext<SidebarContextType | null>(null);
export const SidebarProvider = ({ children }: { children: any }) => {
const [isVisible, setIsVisible] = useState(false);
const toggleSidebar = useCallback(() => {
console.log('--', !isVisible);
setIsVisible(!isVisible);
}, [isVisible]);
return <SidebarContext.Provider value={{ isVisible, toggleSidebar }}>{children}</SidebarContext.Provider>;
};发布于 2022-05-29 20:42:51
也许能帮上忙
const toggleSidebar = useCallback(() => {
setShowSidebar(!showSidebar);
}, [showSidebar]);我认为问题是依赖关系
https://stackoverflow.com/questions/72427078
复制相似问题