请帮助我解决我在 react-router-dom 中的 Link 遇到的问题,如下所示:window.addEventListener("scroll", function() { const theEle = document.getElementById("id-of-div"); const eleTop = theEle.offsetTop; const eleBottom = eleTop + theEle.offsetHeight; console.log("the element of new page", eleTop, eleBottom) });因此,当我将上述脚本放在 X 页中时,在 Y 页中,我有一个<a href='/x'>Link to page X<a> 如果我在 Y 页单击它,那么您当然会转到 X 页并滚动鼠标,窗口检测到鼠标滚动并注销结果但是如果我在 react-router-dom 中使用了 Link 标签,那么会出现一个错误,说 can't get offsetTop of 'id-of-div'<Link to='/x'>Link to page X</Link>我想知道有没有一种方法可以强制 Link 在不使用 a 标签的情况下完成这项工作,因为我真的不希望用户每次从页面 Y 转到 X 时都重新渲染页面 x。
1 回答

婷婷同学_
TA贡献1844条经验 获得超8个赞
显然,如果您渲染其他页面,id-of-div则不再渲染(它会从 DOM 中删除),因此实际上您无法检查它的offsetTop.
解决方案之一是检查内部是否id-of-div存在:
window.addEventListener("scroll", function() {
const theEle = document.getElementById("id-of-div");
if (theEle) {
const eleTop = theEle.offsetTop;
const eleBottom = eleTop + theEle.offsetHeight;
console.log("the element of new page", eleTop, eleBottom);
}
});
然而,更灵活的解决方案是将侦听器不与 . 连接window,而是连接到该页面中的父包装器x。但请记住,在特定情况下这是不可能的(取决于您的组件结构)。
添加回答
举报
0/150
提交
取消