是否可以在 React Router 4 中匹配路由的 # 部分 [英] Is it possible to match the # part of a route in React Router 4

查看:41
本文介绍了是否可以在 React Router 4 中匹配路由的 # 部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我想将路径和哈希值匹配到不同的组件.例如:

In my app, I'd like to match both the path and the hash to different components. For example:

/pageA#modalB

将 PageA 显示为主页面,modalB 位于顶部.我尝试了以下方法,其中包含 path 属性的许多变体:

Would show PageA as the main page, with modalB over the top. I've tried the following, with many variations of the path property:

<Route path="#modalB" component={modalB}/>

但没有任何效果.

在模态控制器"组件内的 React Router 2 中,我会使用:

In React Router 2 inside a modal 'controller' component, I would use:

browserHistory.listen( (location) => { //do something with loction.hash })

我希望在 V4 中有更优雅的东西

I was hoping for something a little more elegant in V4

推荐答案

不是开箱即用的,但 React Router 4 的美妙之处在于它非常容易自己实现.

Not out of the box, but the beauty of React Router 4 is that it's incredibly easy to implement this yourself.

let HashRoute = ({ component: Component, path, ...routeProps }) => (
  <Route 
    {...routeProps}
    component={({ location, ...props }) =>
      location.hash === path && <Component {...props} />
    }
  />
)

<HashRoute path="#modalB" component={ModalB} />

这篇关于是否可以在 React Router 4 中匹配路由的 # 部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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