【发布时间】:2019-12-10 20:26:45
【问题描述】:
我需要为当前路径的名称设置一个类名,例如“inventory”或“about”。但是,当我尝试使用 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>
);
}
}
【问题讨论】:
-
你怎么称呼这个组件?道具需要被某些东西设置在某个地方,它们并不神奇。
-
@F.P 我在我的 App 组件的返回中调用
-
那么你没有任何道具,因为你没有设置它们。使用
useLocation()钩子或withLocation()HOC
标签: javascript reactjs react-router