如何在react-router中创建锚标记? [英] How to create Anchor Tag in react-router?

查看:76
本文介绍了如何在react-router中创建锚标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在内部使用带有react-router的react-boilerplate(3.4.0)进行路由.

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

我试图用以下链接创建一个链接:<a href =#anchor-tag"></a>

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

当我单击它时,我希望使用 id = anchor-tag

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

即使我使用Link组件而不是<,它也只是滚动到页面顶部.A>标记.我们是否必须在意使用<A>或<链接>?

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 > ?

我们应该如何在react-router中创建锚标记?

How should we create anchor tag in react-router ?

推荐答案

这可能会晚一点,但是您可以将其添加到组件中

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();
    }
  }
}

,然后在要导航到的实际元素上,需要添加 ref 属性,如下所示:

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>

link元素将看起来像常规链接:

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

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

或使用react-router:

Or with react-router:

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

这适用于react-router 2.6.1-目前尚不确定更高版本.

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

希望这会有所帮助!

这篇关于如何在react-router中创建锚标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆