【问题标题】:Get the current path in a react component [duplicate]获取反应组件中的当前路径[重复]
【发布时间】:2016-10-25 16:56:31
【问题描述】:

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

我已经尝试了一些常见的嫌疑人,但没有得到任何结果。特别是我认为会通过 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;

【问题讨论】:

  • @QoP 似乎这只会将上下文传递给直接的孩子,对吗?
  • 到子树中的任何组件,jsfiddle.net/3yLn5qzc/11
  • @AnnaMelzer 你能分享你的路由器代码吗
  • 这个问题已经有一年了。我无法再访问那个项目了。

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


【解决方案1】:

先将你的组件添加到路由器

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

你可以得到你的路径

this.props.location.pathname

这是位置自述文件

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

【讨论】:

  • 正如我所说:this.props.location 返回未定义,因此this.props.location.pathname 会引发错误。
  • 你必须将你的组件添加到路由器
猜你喜欢
  • 1970-01-01
  • 2016-06-05
  • 2018-05-06
  • 2013-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-30
  • 1970-01-01
相关资源
最近更新 更多