How to create Anchor Tag in react-router?

感情迁移 提交于 2020-01-02 18:03:50

问题


I am using react-boilerplate (3.4.0) with react-router internally for the routing.

I have tried to create a Link with : < a href="#anchor-tag" >< /a >

When I click on it I expect to scroll to the div with id=anchor-tag

It just scroll to the top of the page, even if I use a Link component instead of a < A > tag. Does we have to care about use < A > or < Link > ?

How should we create anchor tag in react-router ?


回答1:


This might be a while late but what you can do is add this to your component:

import ReactDOM from 'react-dom';

... some more codez...

componentDidUpdate() {
  const anchor = this.props.location.hash.replace('#', '');

  if (anchor) {
    const domElement = ReactDOM.findDOMNode(this.refs[hash]);
    if (domElement) {
      domElement.scrollIntoView();
    }
  }
}

and then on your actual element that you want to navigate to, you need to add the ref attribute, like this:

<h1 ref="my-anchor">Hello World</h1>

The link element is going to look just like a regular link:

<a href="/about#my-anchor>Go To Anchor</a>

Or with react-router:

<Link key="my-anchor" to="/about#my-anchor">Go To Anchor</Link>

This works with react-router 2.6.1 - not sure about later versions at this point.

Hope this helps!




回答2:


Improved answer above:

componentDidMount() {
  const anchor = this.props.location.hash;

  if (anchor) {
    const domElement = document.querySelector(anchor);
    if (domElement) {
      domElement.scrollIntoView();
    }
  }
}



回答3:


I highly recommend to use the package from Rafael Pedicini called react-router-hash-link.

Live example right there. It's working well and the code is clean.



来源:https://stackoverflow.com/questions/41739847/how-to-create-anchor-tag-in-react-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!