要确定特定菜单项的样式,我正在尝试获取导航组件中的当前路径。
我已经尝试了一些常见的嫌疑人,但无法得到任何结果。特别是我认为通过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;
答案 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