[英]How to determine if the current route is active in React
react v0.14.7 / react-router: v2.0.1反应 v0.14.7 /反应路由器:v2.0.1
I have my Routes set up as follows:我的路线设置如下:
import { Router, Route, IndexRoute, hashHistory } from "react-router"
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Index}/>
<Route path="/locations" component={Locations}/>
<Route path="/products" component={Products}/>
</Route>
</Router>,
document.getElementById('app'));
I'm trying to write a method in one of my React classes (created using the following API)我正在尝试在我的一个 React 类中编写一个方法(使用以下 API 创建)
export default class MyClass extends React.Component {...}
...that determines if the current URL's path is a particular route's path. ...确定当前 URL 的路径是否是特定路由的路径。
For example.例如。 Assuming the current URL is
http://domain/products
then calling:假设当前 URL 是
http://domain/products
然后调用:
isActive('/products')
would return TRUE
会返回
TRUE
I'm aware of React Router's Link
object activeClassName
.我知道 React Router 的
Link
对象activeClassName
。 But I need to write something that looks this up programmatically in a different location to where I defined the <link/>
objects.但是我需要编写一些东西,在与我定义
<link/>
对象的位置不同的位置以编程方式查找它。
Looking in node_modules/react-router/
I can see modules/isActive.js
that does what I need, however it's not export
ed in modules/index.js
, so i'm assuming I cannot access it?查看
node_modules/react-router/
我可以看到modules/isActive.js
node_modules/react-router/
我的需要,但是它没有在modules/index.js
export
,所以我假设我无法访问它?
I also see from the API docs that there is an RouterContext isActive method , but again, I don't know how to call this?我还从 API 文档中看到有一个 RouterContext isActive 方法,但同样,我不知道如何调用它?
OK thanks to Mike 'Pomax' Kamermans, I resolved the issue like so:好的,感谢 Mike 'Pomax' Kamermans,我像这样解决了这个问题:
Changed create class API from:将创建类 API 更改为:
export default class MyClass extends React.Component {
...
}
to:到:
export default React.createClass({
...
})
And added the following contextTypes
definition to the class:并将以下
contextTypes
定义添加到类中:
export default React.createClass({
contextTypes: {
router: React.PropTypes.object
},
render(){
console.log(this.context.router.isActive('/foo')); // Now works :)
...
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.