Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

实现一个useBodyScrollLock ,当出现弹窗时 阻止背景滚动

Sunny-117 opened this issue · comments

commented
import { useEffect, useState } from "react";

function useBodyScrollLock() {
  const [isLocked, setIsLocked] = useState(false);

  useEffect(() => {
    const body = document.querySelector("body");

    if (isLocked) {
      body.style.overflow = "hidden";
    } else {
      body.style.overflow = "visible";
    }

    return () => {
      body.style.overflow = "visible";
    };
  }, [isLocked]);

  return [isLocked, setIsLocked];
}

export default useBodyScrollLock;