类型错误:无法读取 null 的属性“getBoundingClientRect”

Wes*_*ley 4 reactjs

我正在尝试创建具有粘性效果的标题,但是在滚动页面时遇到此错误,有时有效,有时会发生错误。谁能帮我解决这个问题吗?

在此输入图像描述

  const EventPage: React.FC = () => {
    const [isSticky, setSticky] = useState(false);
    const ref = useRef(null);

    const handleScroll = () => {
      if (ref.current.getBoundingClientRect().y <= -580 || null) {
        console.log(ref.current.getBoundingClientRect().y);

        setSticky(true);
      } else {
        setSticky(false);
      }
    };

    useEffect(() => {
      window.addEventListener("scroll", handleScroll);

      return () => {
        window.removeEventListener("scroll", () => handleScroll);
      };
    }, []);

    return (
      <div>
        <Head>
          <title>Event Page</title>
        </Head>
        <Header />
        <div className={`sticky-wrapper${isSticky ? " sticky" : ""}`} ref={ref}>
          {isSticky && <Sticky />}
        </div>
Run Code Online (Sandbox Code Playgroud)

gau*_*its 7

refs 在重新渲染时可以为 null,因此在访问元素 refs 的属性之前始终进行 null 检查。以下是盖伦对裁判的评价。

const handleScroll = () => {
      if(!ref.current) return
      if (ref.current.getBoundingClientRect().y <= -580 || null) {
        console.log(ref.current.getBoundingClientRect().y);

        setSticky(true);
      } else {
        setSticky(false);
      }
    };
Run Code Online (Sandbox Code Playgroud)