ReactJS在URL中使用“#”,所以当我写:
<a href="#specificAreaId" >Click here to scroll to top</a>
它不能用作滚动到具有id:specificAreaId的元素。相反,它导航到另一个页面。有人能给我这样做的想法吗?
您是否按照指定的方式创建锚点https://www.w3.org/MarkUp/1995-archive/Elements/A.html
你可以使用react-scrollable-anchor
安装它:
npm install --save react-scrollable-anchor
并将其导入您的组件:
import ScrollableAnchor from 'react-scrollable-anchor'
然后使用它像:
<a href='#myScrollSection'> Go to myScrollSection </a>
<ScrollableAnchor id={'myScrollSection'}>
<div> Hello World </div>
</ScrollableAnchor>
你可以阅读更多here
我假设您在hash history
中使用react-router
。你能尝试使用browser history
吗?
如果你创建锚标签,它也是理想的:
<a href="pageUrl#specificAreaId" >Click here to scroll to top</a>
您也可以参考这篇文章,关于类似的问题:
你可以试试'jquery animate scrollTop'。
$('html, body').animate({
scrollTop: $('#specificAreaId').offset().top
}, 800);