react-router 是否支持相对链接? [英] Does react-router support relative links?

查看:34
本文介绍了react-router 是否支持相对链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个网址上:

/path1/path2

那么:

<Link to="path2/path3" />

使用此代码,地址栏中的地址更改为:

With this code the address in the address bar is changed to:

/path1/path2/path3

它似乎有效:它已转到最后一个 / 并添加了新路径.但是,实际上,虽然它更改了地址栏中的 url,但不会发生导航.

It seems to have worked: it has gone to the last / and added the new path to that. But, in fact, while it changes the url in the address bar no navigation happens.

看起来链接必须提供绝对网址?

It looks like Links have to be given absolute urls?

推荐答案

在 react-router v4 中支持相对路径.history 库就像浏览器一样"解析相对路径,以便

in react-router v4 relative paths are supported. The history library resolves relative paths 'just like a browser would' so that a

<Link to="two" />

或一个

history.push({ pathname: '..', search: 'foo=bar' });

在 url site.com/path/one 将重定向到 site.com/path/twosite.com/three?foo=bar.

at the url site.com/path/one will redirect to site.com/path/two and site.com/three?foo=bar.

然而,NavLink 不适用于相对路径名,因为它不能解析它自己的相对路径(这很重要).然而,有一些社区包,但我还没有测试过.

However NavLink does not work with relative pathnames because it doesn't resolve it's own relative path (which is nontrivial to do). However there are some community packages for this, but I haven't tested them.

或者,这就是我所做的,您可以从您的父路由(或从上下文 router.route.match)获取一个 match 对象并使用它在 NavLink 中构建您的相对 to:

Alternatively, and this is what I do, you can get a match object from your parent Route (or from the context router.route.match) and use it to build your relative to in NavLink:

<NavLink to={`${match.url}/three`} />

这样你的组件就可以独立于它的父路由工作.

this way your component can work independent of it's parent Route(s).

这篇关于react-router 是否支持相对链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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