繁体   English   中英

如何确定当前路由在 React 中是否处于活动状态

[英]How to determine if the current route is active in React

反应 v0.14.7 /反应路由器:v2.0.1

我的路线设置如下:

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'));

我正在尝试在我的一个 React 类中编写一个方法(使用以下 API 创建)

export default class MyClass extends React.Component {...}

...确定当前 URL 的路径是否是特定路由的路径。

例如。 假设当前 URL 是http://domain/products然后调用:

isActive('/products')

会返回TRUE

我知道 React Router 的Link对象activeClassName 但是我需要编写一些东西,在与我定义<link/>对象的位置不同的位置以编程方式查找它。

查看node_modules/react-router/我可以看到modules/isActive.js node_modules/react-router/我的需要,但是它没有在modules/index.js export ,所以我假设我无法访问它?

我还从 API 文档中看到有一个 RouterContext isActive 方法,但同样,我不知道如何调用它?

好的,感谢 Mike 'Pomax' Kamermans,我像这样解决了这个问题:

将创建类 API 更改为:

export default class MyClass extends React.Component {

    ...  

}

到:

export default React.createClass({
    ...
})

并将以下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.

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