reactjs 如何停止React中固定元素的后台滚动?

m0rkklqb  于 2022-12-26  发布在  React
关注(0)|答案(1)|浏览(141)

我正在使用NextJS与tailwind.和我正在创建一个抽屉,弹出窗口和模态与position: fixed .所以当我实现这一点,并滚动它的背景组件将滚动以及.即使固定是滚动时,滚动结束后,元素开始滚动.我怎么才能使它停止的背景是不可滚动和可点击?

function Drawer() {
  const toggle = useSelector(selectMenu);
  const dispatch = useDispatch();
  const handleOnClose = (e) => {
    if (e.target.id === "container") dispatch(toggleMenu(!toggle));
  };
  return (
    <div
      id="container"
      onClick={handleOnClose}
      className={`md:hidden h-full w-full backdrop-blur-sm fixed ${
        !toggle && "hidden"
      }`}
    >
      <div
        className={`${
          toggle ? " translate-x-0" : "translate-x-full"
        } md:hidden fixed h-screen w-3/4 ease-in-out duration-300 bg-white z-50 bottom-0 top-0 right-0 flex flex-col px-4 py-3 space-y-5 shadow-2xl`}
      >
        <Link
          href="/"
          className="cursor-pointer flex px-2 space-x-4"
          onClick={() => dispatch(toggleMenu(!toggle))}
        >
          <HomeModernIcon className="h-6 w-6 text-black" />
          <h1>Dashboard</h1>
        </Link>
        <div className=" h-[1px] w-full bg-gray-600" />
        <Link
          href="/clients"
          className="cursor-pointer flex px-2 space-x-4"
          onClick={() => dispatch(toggleMenu(!toggle))}
        >
          <TruckIcon className="h-6 w-6 text-black" />
          <h1>Clients</h1>
        </Link>
        <div className=" h-[1px] w-full bg-gray-600" />
        <Link
          href="/employee"
          className="cursor-pointer flex px-2 space-x-4"
          onClick={() => dispatch(toggleMenu(!toggle))}
        >
          <PuzzlePieceIcon className="h-6 w-6 text-black" />
          <h1>Employee</h1>
        </Link>
        <div className=" h-[1px] w-full bg-gray-600" />
        <Link
          href="/services"
          className="cursor-pointer flex px-2 space-x-4"
          onClick={() => dispatch(toggleMenu(!toggle))}
        >
          <WrenchIcon className="h-6 w-6 text-black" />
          <h1>Services</h1>
        </Link>
      </div>
    </div>
  );
}
jmo0nnb3

jmo0nnb31#

Modal组件中添加此useEffect。由于您使用的是tailwind-css,因此将overflow-hidden className添加到body元素中

useEffect(() => {
    // this will disable the scroll if our back page was scrollable
    document.body.classList.add("overflow-hidden");
    // when you close the modal, remove this class 
    return () => {
      document.body.classList.remove("overflow-hidden");
    };
  }, []);

相关问题