简体   繁体   中英

React anchor tag keeps redirecting to the top of the page when clicked

I have anchor tags in the header of my React web page. The web page has multiple components with ID's in the html so that the anchor tags can go to certain sections when clicked. However, whenever I click an anchor tag, it takes me to the section then it snaps right back to the top of the page. This happens regardless of which anchor tag I click and it happens no matter the id that is in the href.

The code is just typical React code rendering HTML. I am not sure why this is happening. Any help is greatly appreciated, thanks.

function Header () {
  return (
      <header id="header">
        <nav>
            <ul className="nav-menu">
                <li className="menu-active"><a className="nav-link" href="virtualLF">Home</a></li>
                <li><a className="nav-link" href="#about">About</a></li>
                <li><a className="nav-link" href="#schedule">Agenda</a></li>
                <li><a className="nav-link" href="#speakers">Speakers</a></li>
                <li><a className="nav-link" href="#sponsors">Sponsors</a></li>
                <li><a className="nav-link" href="#contact">Contact</a></li>

Yes, anchor links doesn't work with React in that way. I would recommend installing react-router ( ref here ) and use HashLink from this library for that purpose ( ref here )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM