javascript - 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>
);
};
解决方案
关注文章https://medium.com/@teh_builder/ref-objects-inside-useeffect-hooks-eb7c15198780。它展示了如何通过 useEffect 使用 refs。
推荐阅读
- javascript - 使用 Javascript 从 JSON 对象动态生成引导网格 HTML
- javascript - 我的代码凌乱且浪费行,如何使我的代码简单
- javascript - 异步函数不返回数据库查询数据
- java - Hazelcast - QueueListener - 多线程或 MDB
- python-3.x - Python:如何从日期时间列中提取的月份列中获取模式?
- ios - CollectionView 在视图层次调试器上可见,但在模拟器上不可见
- html - FormSubmit 说我的表单应该使用 method=POST 但实际上确实如此
- android - 每 X 秒触发一次 Intent 服务,性能有何不同?
- python - 以编程方式访问指定 Google 表格的活动
- python - 使用 YOLO 和 OpenCV 时出现错误 - No such file or directory: 'labels.txt'