【问题标题】:TypeError: Cannot read property 'getBoundingClientRect' of nullTypeError:无法读取 null 的属性“getBoundingClientRect”
【发布时间】:2020-08-08 13:15:05
【问题描述】:

我正在尝试创建具有粘性效果的标题,但在滚动页面时出现此错误,有时它可以工作,有时会发生错误。谁能帮我解决这个问题?

  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>

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    refs 在重新渲染时可以为 null,因此在访问元素 refs 的属性之前总是检查 null。以下是gaearon 对 refs 的看法。

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

    【讨论】:

    • 当 ref.current 为假时,代码不应继续。你能检查一下为什么它应该在 falsy ref.current 的情况下返回。
    【解决方案2】:

    抱歉写晚了。

    if(status: solved)
    {
      **CONGRATULATIONS**
    }
    
    else{
    

    好吧,我猜问题不在您的 JS 文件中,可能是在您的 .html 文件中。去那里,或者在你链接你的 JS 文件的地方使用 defer,或者把它放在你的目标元素下。 这可能有用,至少对我有用! }

    【讨论】:

      猜你喜欢
      • 2021-02-27
      • 2019-05-31
      • 1970-01-01
      • 2021-04-17
      • 2021-03-02
      • 2023-03-10
      • 2020-01-29
      • 2022-01-12
      • 2021-12-04
      相关资源
      最近更新 更多