reactjs – 获取反应组件中的当前路径

前端之家收集整理的这篇文章主要介绍了reactjs – 获取反应组件中的当前路径前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > react-router getting this.props.location in child components1个
要确定特定菜单项的样式,我试图获取导航组件中的当前路径.

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

this.props.location返回undefined

this.props.context返回undefined

我使用react 15,redux 3.5,react-router 2,react-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;
首先将组件添加到路由器
<Router path="/" component={Navigation}  />

你可以进入你的道路

this.props.location.pathname

这是位置的自述文件

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

原文链接:https://www.f2er.com/react/300779.html

猜你在找的React相关文章