获取react组件中的当前路径

时间:2016-06-23 11:23:09

标签: reactjs react-router react-router-redux

要确定特定菜单项的样式,我正在尝试获取导航组件中的当前路径。

我已经尝试了一些常见的嫌疑人,但无法得到任何结果。特别是我认为通过React注入的属性不存在。

this.props.location返回undefined

this.props.context返回undefined

我使用react 15redux 3.5react-router 2react-router-redux 4

import React, {Component, PropTypes} from 'react';
import styles from './Navigation.css';
import NavigationItem from './NavigationItem';

class Navigation extends Component {

  constructor(props) {
    super(props);
  }

  getNavigationClasses() {
    let {navigationOpen, showNavigation} = this.props.layout;
    let navigationClasses = navigationOpen ? styles.navigation + ' ' + styles.open : styles.navigation;
    if (showNavigation) {
      navigationClasses = navigationClasses + ' ' + styles.collapsed;
    }
    return navigationClasses;
  }

  render() {
  /*
  TODO:  get pathname for active marker
  */

    let navigationClasses = this.getNavigationClasses();
    return (
      <div
        className={navigationClasses}
        onClick={this.props.onToggleNavigation}
      >

        {/* Timeline */}
        <NavigationItem
          linkTo='/timeline'
          className={styles.navigationItem + ' ' + styles.timeline}
          displayText='Timeline'
          iconType='timeline'
        />

        {/* Contacts */}
        <NavigationItem
          linkTo='/contacts'
          className={styles.navigationItem + ' ' + styles.contact + ' ' + styles.active}
          displayText='Contacts'
          iconType='contacts'
        />

      </div>
    );
  }
}

Navigation.propTypes = {
  layout: PropTypes.object,
  className: PropTypes.string,
  onToggleNavigation: PropTypes.func
};

export default Navigation;

1 个答案:

答案 0 :(得分:15)

首先将您的组件添加到路由器

<Router path="/" component={Navigation}  />

您可以在

中找到自己的路径
this.props.location.pathname

这是位置的自述文件

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/location.md