为什么我的 React + Tailwind 汉堡包菜单没有关闭?

Why Is My React + Tailwind Hamburger Menu Not Closing?

我正在使用 React 和 TailwindCSS 构建一个汉堡菜单。单击 'X' 按钮时,我将状态 isOpen 更改为 false。包裹菜单的 div 的 class 响应状态变化,但菜单不会滑出。我在这里错过了什么?

Sidebar.js:

const Sidebar = () => {
  const [isOpen, toggleSidebar] = React.useState(true);
  return (
    <div className="h-screen flex">
      <div
        className={`fixed z-30 inset-y-0 left-0 w-64 px-8 py-4 bg-gray-100 border-r overflow-auto lg:static  lg:inset-auto lg:translate-x-0 ${
          isOpen
            ? "translate-x-0 ease-out transition-medium"
            : "-translate-x-full ease-in transition-medium"
        }`}
      >
        <div className="-mx-3 pl-3 pr-1 flex items-center justify-between">
          <span>
            <p className="h-10 w-10">Logo</p>
          </span>
          <button
            onClick={() => toggleSidebar(false)}
            className="text-gray-700 lg:hidden"
          >
            <svg fill="none" viewBox="0 0 24 24" className="h-6 w-6">
              <path
                d="M6 18L18 6M6 6L18 18"
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth="2"
                stroke="currentColor"
              />
            </svg>
          </button>
        </div>
        <nav className="mt-8">
          <h3 className="text-xs font-semibold text-gray-600 uppercase tracking-wide">
            STUFF
          </h3>
          <button className="mt-2 -ml-1 flex items-center text-sm font-medium text-gray-600">
            <svg
              className="h-5 w-5 text-gray-500"
              viewBox="0 0 24 24"
              fill="none"
            >
              <path
                d="M12 7v10m5-5H7"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
              />
            </svg>
            <span className="ml-1">Add Stuff</span>
          </button>
        </nav>
      </div>
    </div>
  );
};

ReactDOM.render(<Sidebar />, document.getElementById("root"));

This 是我脚本的代码笔,如果有帮助的话:

根据 Tailwind 文档,您需要添加 transform 实用程序。
https://tailwindcss.com/docs/translate/#usage

Translate an element by first enabling transforms with the transform utility, then specifying the translate direction and distance using the translate-x-{amount} and translate-y-{amount} utilities.

所以在class中添加transform

className={`
fixed z-30 inset-y-0 left-0 w-64 px-8 py-4 bg-gray-100 border-r 
overflow-auto lg:static  lg:inset-auto lg:translate-x-0 

transform ${
          isOpen
            ? "translate-x-0 ease-out transition-medium"
            : "-translate-x-full ease-in transition-medium"
        }`}