【问题标题】:How to determine if the current route is active in React如何确定当前路由在 React 中是否处于活动状态
【发布时间】:2016-06-28 17:35:06
【问题描述】:

react v0.14.7 / react-router: 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。但是我需要在与我定义 &lt;link/&gt; 对象的位置不同的位置以编程方式进行查找。

查看node_modules/react-router/ 我可以看到modules/isActive.js 可以满足我的需要,但它不是modules/index.js 中的exported,所以我假设我无法访问它?

我也看到了from the API docs that there is an RouterContext isActive method,但是我又不知道怎么称呼这个?

【问题讨论】:

  • this.context.router.isActive 不适合你?
  • @Oleg,似乎没有。我收到一个 JS 控制台错误:“TypeError: this.context.router is undefined”
  • 您忘记添加的非常重要的信息:哪个版本的 react-router? (如果是2.0,你还记得specify the context吗?)
  • 对不起,是的。我正在使用 react-router v2.0.1

标签: javascript node.js reactjs react-router


【解决方案1】:

好的,感谢 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 :)

    ...
  }

})

【讨论】:

猜你喜欢
  • 2016-08-29
  • 2012-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-17
  • 1970-01-01
相关资源
最近更新 更多