如何使用反应路由器的普通锚链接 [英] How to use normal anchor links with react-router

查看:214
本文介绍了如何使用反应路由器的普通锚链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常类似于这个有争议的问题:怎么做当使用react-router时,我使用锚链接进行页内导航?

Very similar to this angular question: how do I use anchor links for in-page navigation when using react-router?

换句话说,在使用react-router时如何实现以下纯HTML?

In other words, how do I implement the following plain HTML when using react-router?

<a href="#faq-1">Question 1</a>
<a href="#faq-2">Question 2</a>
<a href="#faq-3">Question 3</a>

<h3 id="faq-1">Question 1</h3>
<h3 id="faq-2">Question 2</h3>
<h3 id="fa1-3">Question 3</h3>

目前我拦截了对此类链接的点击,并滚动到锚点位置。这并不令人满意,因为这意味着无法直接链接到页面的某个部分。

Currently I intercept clicks on such links, and scroll to the anchor position. This isn't satisfactory, because it means it's impossible to link directly to some section of a page.

推荐答案

锚的问题链接是react-router的默认设置是使用URL中的哈希来维护状态。幸运的是,您可以根据位置文档更换其他内容的默认行为。在您的情况下,您可能希望使用HistoryLocation对象尝试干净的URL,这意味着react-router不会使用URL哈希。试试这样:

The problem with anchor links is that react-router's default is to use the hash in the URL to maintain state. Fortunately, you can swap out the default behaviour for something else, as per the Location documentation. In your case you'd probably want to try out "clean URLs" using the HistoryLocation object, which means react-router won't use the URL hash. Try it out like this:

Router.run(routes, Router.HistoryLocation, function (Handler) {
  React.render(<Handler/>, document.body);
});

这篇关于如何使用反应路由器的普通锚链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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