簡體   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