Home > Web Front-end > JS Tutorial > body text

How to implement anchor scrolling in react

王林
Release: 2020-12-23 10:56:43
forward
3530 people have browsed it

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>   //跳转到的锚点
但是在单页面中,这样会进行前端路由的修改
Copy after login

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;}); }
    }
  }
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template