Home > Article > Web Front-end > How to implement anchor scrolling in react
Tips:
To implement anchor scrolling, do not use the a tag, because this will cause routing jumps.
(Learning video sharing: react video tutorial)
The new API of H5 is used here, scrollToAnchor
Previous method of using a tag:
<a href='#activity1'></a> //定义锚点 <div name='activity1'></div> //跳转到的锚点 但是在单页面中,这样会进行前端路由的修改
Use scrollToAnchor API to modify
<a onClick={() => this.scrollToAnchor(name)}></a> //定义锚点 <div id='activity1'></div> //跳转到的锚点 //函数定义 scrollToAnchor = (anchorName) => { if (anchorName) { // 找到锚点 let anchorElement = document.getElementById(anchorName); // 如果对应id的锚点存在,就跳转到锚点 if(anchorElement) { anchorElement.scrollIntoView({block: 'start', behavior: 'smooth'}); } } }
block: indicates scrolling to the top or bottom of the anchor point, start/end
behavior: indicates the effect of scrolling, auto/instant/ smooth (scrolling effect)
1. Change the traditional name attribute of the anchor point to the id attribute. In this way, we can use the document.getElementById method to conveniently query the anchor point.
2. Remove the href attribute of the original red button, and then add an onClick method. The onClick method passes in the id of an anchor point, and then uses the following function to find the anchor point and jump to the anchor point.
Related recommendations: react tutorial
The above is the detailed content of How to implement anchor scrolling in react. For more information, please follow other related articles on the PHP Chinese website!