简体   繁体   English

使用React-Router的程序化相对链接

[英]Programmatic relative links with react-router

Did somebody manage to find a good way how to programmatically navigate to a relative link with react-router? 有人设法找到一种很好的方法来以编程方式使用react-router导航到相对链接吗?

I've used react-router-relative-links for declarative links, but I can't find a good way to do this programmatically. 我已经使用了react-router-relative-links来进行声明式链接,但是我找不到以编程方式进行此操作的好方法。

I know it could be done manually with resolve-pathname and router.push(…) , but that would require access to the location , which is only available on route handler components. 我知道可以使用resolve-pathnamerouter.push(…)手动完成此操作,但这需要访问location ,该location仅在路由处理程序组件上可用。 My component is somewhat deep down the tree, therefore I'd like to avoid all the wiring back to the top. 我的组件在树的深处,因此,我希望避免所有的布线都回到顶部。

Is window.location.pathname the right way to get the location and then use router.push available through withRouter ? window.location.pathname是获取位置然后通过withRouter使用router.push的正确方法吗?

Currently I'm using this as a utility function: 目前,我正在将其用作实用程序功能:

import resolvePathname from 'resolve-pathname';

function getPathnameFromRelativeLocation(relativeLocation) {
  let {pathname} = window.location;
  let basePath = pathname.endsWith('/') ? pathname : pathname + '/';
  return resolvePathname(relativeLocation, basePath);
}

And in an event handler of a React component: 在React组件的事件处理程序中:

// Current path is `/books/123`
let path = getPathnameFromRelativeLocation('write-review');
this.props.router.push(path);
// Current path is `/books/123/write-review`

react-router 3.0 now provides location on the context so it's now easy to just take it from there. react-router 3.0现在在上下文中提供了location ,因此现在很容易从那里获取它。

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

if you are using browserHistory it's simply 如果您使用的是browserHistory,那么

browserHistory.push('/yourRelativePath');

for that make sure you have latest react-router and 为此,请确保您拥有最新的React-Router和

 import { browserHistory } from 'react-router';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM