javascript - React中如何判断当前路由是否活跃

标签 javascript node.js reactjs react-router

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 。但我需要编写一些内容,以编程方式在与我定义 <link/> 的位置不同的位置进行查找。对象。

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

我还看到from the API docs that there is an RouterContext isActive method ,但我又不知道如何调用它?

最佳答案

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

    ...
  }

})

关于javascript - React中如何判断当前路由是否活跃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35974686/

相关文章:

node.js - 如何使用 sequelize-typescript 从源实例创建关联实例

node.js - React 不会切换到生产模式

javascript - Swig (Node.js) 中的 JSON.parse() ?

javascript - React Hooks - 设置最后一个值?

javascript - 为什么 javascript 会改变 Array.push 上的数据类型?

php - 如何通过输出数组的每一行的特定一个属性来运行 htmlentities()

javascript - 使用 JavaScript 在 div 上随机分布 HTML 元素

c# - 如何使用asp.net C#计算文件上传和下载时间

node.js - react /Node : Dynamic host and port (client & server) for current run-time environment

javascript - 在 redux 操作中查询 api 时出现无限循环