首页 > 解决方案 > React useRef 在路由更改时返回无法读取 null 属性“样式”的错误

问题描述

我对控制平滑滚动的组件有疑问。刷新页面时,我的问题为零,但在 RouteChanges 上,我得到了回复Cannot read property 'style' of null

清楚地并得到组件中的错误的支持,Object is possibly 'undefined'.ts(2532)我知道在路由更改中ref尚未应用。但是,我无法弄清楚如何解决。查看其他类似问题的问题,他们都建议使用useEffect(),我就是。我究竟做错了什么?

该组件是

const Scroll: React.FC = ({ children }) => {
  const windowSize = useWindowSize();
  const scrollingContainerRef = useRef();

  const data = {
    ease: 0.1,
    current: 0,
    previous: 0,
    rounded: 0,
  };

  const setBodyHeight = () => {
    if (isBrowser)
      document.body.style.height = `${
        scrollingContainerRef.current.getBoundingClientRect().height // Object is possibly 'undefined'.ts(2532)

      }px`;
  };

  useEffect(() => {
    setBodyHeight();
  }, [windowSize.height]);

  const smoothScrollingHandler = () => {
    data.current = isBrowser && window.scrollY;
    data.previous += (data.current - data.previous) * data.ease;
    data.rounded = Math.round(data.previous * 100) / 103;
    scrollingContainerRef.current.style.transform = `translateY(-${data.previous}px)`; // Object is possibly 'undefined'.ts(2532)

    requestAnimationFrame(() => smoothScrollingHandler());
  };

  useEffect(() => {
    requestAnimationFrame(() => smoothScrollingHandler());
  }, []);

  return (
    <Wrapper>
      <div ref={scrollingContainerRef}>{children}</div>
    </Wrapper>
  );
};

标签: javascriptreactjs

解决方案


关注文章https://medium.com/@teh_builder/ref-objects-inside-useeffect-hooks-eb7c15198780。它展示了如何通过 useEffect 使用 refs。


推荐阅读