react-router <Link/>通配符路径匹配 [英] react-router <Link/> Wildcard Path Matching
问题描述
在我的应用程序中,我有一个 <NavBar/>
组件和一些链接,这些链接告诉后端在指定的状态下返回一个随机的 location_id
.这很好用,但是因为我 browserHistory.replace()
返回 location_id
路径的 random
路径
不再匹配路由器路径,因此不会保持 active
.有没有办法让 <Link/>
组件匹配每个 location_id
包括 random
,即一个 MA如果 url 为
/locations/MA/1
、/locations/MA/random
或更一般的 /locations/MA/*,code> 链接将保持活动状态代码>.但继续指向
locations/MA/random
?
In my application, I have a <NavBar/>
component with a few links which tell the back-end to return a random location_id
in the specified State. This works well, but because I browserHistory.replace()
the random
path with the returned location_id
path the <NavLink/>
no longer matches the router path and therefore doesn't remain active
. Is there a way to make the <Link/>
component match for every location_id
including random
, i.e. a MA
link would remain active if the url were /locations/MA/1
, /locations/MA/random
, or more generally /locations/MA/*
. but continue to point to locations/MA/random
?
/* ./modules/NavLink.js */
import React from 'react'
import { Link } from 'react-router'
export default React.createClass({
render() {
return <Link {...this.props} activeClassName="active"/>
}
})
/* Main use of the <NavLink/> */
<NavLink to="/locations/MA/random">Massachusetts</NavLink>
推荐答案
一种方法是将组件的 'to' 属性配置为/locations/MA",以便它对所有/locations/MA"保持活动状态/*".但是将它绑定到这样的onClick"函数
One way to do it is configure the 'to' attribute of component to "/locations/MA" so that it remains active for all "/locations/MA/*". But bind it to a 'onClick' function like this
const onLinkClick = (evt) => {
evt.preventDefault()
history.push('locations/MA/random')
}
现在虽然它对所有匹配都保持活动状态,但它只会导航到一个 URL
Now although it remains active for all matches, it will only navigate to one URL
这篇关于react-router <Link/>通配符路径匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!