reactjs - Reactjs nav 平滑滚动和路由
问题描述
有人可以帮我吗,我设计了一个自定义导航栏,当您单击链接时,它会平滑滚动到该组件。问题是,当我在另一条路线上(示例:/shop)并单击导航栏链接时,它会在“getBoundingClientReact null”上显示错误。我知道 useEffect 在 html 内容更改之前运行,但我还没有找到任何解决方案。
您可以在此处查看代码以更好地理解问题。
解决方案
您收到此错误,因为正如错误所说targetSection
,null
因此不能在其上调用任何方法,targetSection
为 null 因为在 component/ViewPort.js, LINE 33const targetSection = document.querySelector("#" + targetId);
中,您分配null
给targetSection
因为没有任何 id 等于的元素targetId
.
这是正确的,因为当您在 path 上时/shop
,React 会呈现您的ShopScreen
组件,并且该组件不包含任何 id 为 on 的元素HomeScreen
。您需要SmoothScroll
在重定向到之后调用您的/
,而不是之前。
编辑:作为一个方便的解决方案,我建议用<Link>
来自<HashLink>
https://github.com/rafgraph/react-router-hash-link 的组件react-router-hash-link
和cssscroll-behavior: smooth
属性替换。这样你根本不需要调用SmoothScroll
,代码会更简单。