首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我的侧边栏在从我的自定义钩子调用函数时不打开?

为什么我的侧边栏在从我的自定义钩子调用函数时不打开?
EN

Stack Overflow用户
提问于 2022-05-29 20:31:50
回答 2查看 40关注 0票数 0

我有一段代码:

我的定制钩:

代码语言:javascript
复制
export const useSidebar = () => {
  const [showSidebar, setShowSidebar] = useState(false);

  const toggleSidebar = useCallback(() => {
    setShowSidebar(!showSidebar);
  }, [showSidebar]);

  return [showSidebar, toggleSidebar] as const;
};

我的边栏:

代码语言:javascript
复制
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

你能指出我做错了什么吗?

非常感谢。

在Stackblitz上运行

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-05-29 21:14:27

好的,我的错误我不能用钩子来做,所以我用了一个上下文。

代码语言:javascript
复制
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>;
};
票数 2
EN

Stack Overflow用户

发布于 2022-05-29 20:42:51

也许能帮上忙

代码语言:javascript
复制
  const toggleSidebar = useCallback(() => {
    setShowSidebar(!showSidebar);
  }, [showSidebar]);

我认为问题是依赖关系

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72427078

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档