猿问

如何在 react-router-dom 中使用 <Link> 标签重新渲染整个页面

请帮助我解决我在 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。


慕丝7291255
浏览 322回答 1
1回答

婷婷同学_

显然,如果您渲染其他页面,id-of-div则不再渲染(它会从 DOM 中删除),因此实际上您无法检查它的offsetTop.解决方案之一是检查内部是否id-of-div存在:window.addEventListener("scroll", function() {&nbsp; &nbsp; const theEle = document.getElementById("id-of-div");&nbsp; &nbsp; if (theEle) {&nbsp; &nbsp; &nbsp; &nbsp;const eleTop = theEle.offsetTop;&nbsp; &nbsp; &nbsp; &nbsp;const eleBottom = eleTop + theEle.offsetHeight;&nbsp; &nbsp; &nbsp; &nbsp;console.log("the element of new page", eleTop, eleBottom);&nbsp; &nbsp; }});然而,更灵活的解决方案是将侦听器不与 . 连接window,而是连接到该页面中的父包装器x。但请记住,在特定情况下这是不可能的(取决于您的组件结构)。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答