Home  >  Article  >  Web Front-end  >  How to implement anchor scrolling in react

How to implement anchor scrolling in react

王林
王林forward
2020-12-23 10:56:433499browse

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=&#39;#activity1&#39;></a>    //定义锚点
<div name=&#39;activity1&#39;></div>   //跳转到的锚点
但是在单页面中,这样会进行前端路由的修改

Use scrollToAnchor API to modify

<a onClick={() => this.scrollToAnchor(name)}></a>    //定义锚点

<div id=&#39;activity1&#39;></div>   //跳转到的锚点
//函数定义
scrollToAnchor = (anchorName) => {
    if (anchorName) {
        // 找到锚点
        let anchorElement = document.getElementById(anchorName);
        // 如果对应id的锚点存在,就跳转到锚点
        if(anchorElement) { anchorElement.scrollIntoView({block: &#39;start&#39;, behavior: &#39;smooth&#39;}); }
    }
  }

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete