在 react-router 中使用锚点 [英] Use anchors with react-router

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

问题描述

如何使用 react-router 并让链接导航到特定页面上的特定位置?(例如/home-page#section-three)

How can I use react-router, and have a link navigate to a particular place on a particular page? (e.g. /home-page#section-three)

详情:

我在我的 React 应用程序中使用了 react-router.

I am using react-router in my React app.

我有一个站点范围的导航栏,需要链接到页面的特定部分,例如 /home-page#section-three.

I have a site-wide navbar that needs to link to a particular parts of a page, like /home-page#section-three.

因此,即使您在说 /blog,单击此链接仍会加载主页,第三部分会滚动到视图中.这正是标准

So even if you are on say /blog, clicking this link will still load the home page, with section-three scrolled into view. This is exactly how a standard <a href="/home-page#section-three> would work.

注意:react-router 的创建者没有给出明确的答案.他们说它正在进行中,同时使用其他人的答案.我会尽我最大的努力让这个问题随着进度的更新而更新.可能的解决方案,直到出现占主导地位的解决方案.

Note: The creators of react-router have not given an explicit answer. They say it is in progress, and in the mean time use other people's answers. I'll do my best to keep this question updated with progress & possible solutions until a dominant one emerges.

研究:

如何使用带有 react-router 的普通锚链接

这个问题来自 2015 年(反应时间是 10 年前).最受欢迎的答案是使用 HistoryLocation 而不是 HashLocation.基本上这意味着将位置存储在窗口历史记录中,而不是散列片段中.

This question is from 2015 (so 10 years ago in react time). The most upvoted answer says to use HistoryLocation instead of HashLocation. Basically that means store the location in the window history, instead of in the hash fragment.

坏消息是...即使使用 HistoryLocation(大多数教程和文档在 2016 年都这么说),锚标签仍然不起作用.

Bad news is... even using HistoryLocation (what most tutorials and docs say to do in 2016), anchor tags still don't work.

https://github.com/ReactTraining/react-router/issues/394

ReactTraining 上的一个线程,关于如何将锚链接与 react-router 一起使用.这不是确定的答案.请注意,因为大多数建议的答案已过时(例如,在 中使用hash"道具)

A thread on ReactTraining about how use anchor links with react-router. This is no confirmed answer. Be careful since most proposed answers are out of date (e.g. using the "hash" prop in <Link>)

推荐答案

React Router Hash Link 为我工作并且易于安装和实施:

React Router Hash Link worked for me and is easy to install and implement:

$ npm install --save react-router-hash-link

在你的 component.js 中将其作为链接导入:

In your component.js import it as Link:

import { HashLink as Link } from 'react-router-hash-link';

并且不使用锚点 ,而是使用 :

And instead of using an anchor <a>, use <Link> :

<Link to="home-page#section-three">Section three</Link>

注意:我使用了HashRouter 而不是 路由器:

Note: I used HashRouter instead of Router:

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

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