如何在 react-router 中使用普通锚链接 [英] How to use normal anchor links with react-router

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

问题描述

非常类似于这个角度问题:怎么做使用 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 中的 hash 来维护状态.幸运的是,您可以根据 位置文档将默认行为替换为其他内容.在您的情况下,您可能想使用 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);
});

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

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