我需要将一个类名称设置为当前路径的名称,例如“清单”或“关于”。但是,当我尝试使用this.props.location时,它始终是未定义的。有人可以向我解释为什么会这样吗?
class Header extends Component{
render(){
return(
<Router>
<div className={'header ' + this.props.location}>
<div className="header-content">
<div className="header-right">
<NavLink exact to="/">Home</NavLink>
<NavLink to="/about">About</NavLink>
<NavLink to="/inventory">Inventory</NavLink>
</div>
</div>
</div>
<div className="page-content">
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/inventory" component={Inventory}/>
</div>
</Router>
);
}
}
答案 0 :(得分:0)
这里的事情是history
,location
和blah blah被整合到<Route />
中的组件中,但是您试图从相同的组件访问它们路由器已创建。所以或者您在当前的父文件中创建了路由器,或者使用了窗口对象
<div className={'header ' + window.location}>
答案 1 :(得分:0)
我认为您应该将路由器在层次结构中上移,理想情况下应移至呈现App组件的组件,如下所示:
<Router history={history}>
<App />
</Router>
您当前正在尝试从道具中读取位置,但是由于将Router渲染在同一组件中,因此它无法将位置传递给道具,因此它将始终为空。 如果您通过路由器包装应用,则可以将位置道具传递到需要它的任何其他组件(例如标头)。