【发布时间】:2018-04-28 03:24:25
【问题描述】:
我有一个简单的应用程序,它使用来自 'react-router-dom' v4 的 BrowserRouter。我试图从<BrowserRouter/> 组件中访问location.pathname 属性,但无济于事:
class App extends Component{
render(){
return (
<BrowserRouter>
// How do I access this.props.location?
<div className={(this.props.location.pathnme === "/account") ? "bgnd-black" : "bgnd-white"} >
<Switch>
<Route path="/login" component={LoginPage}/>
<Route path="/success" component={LoginSuccess}/>
<Route path="/account" component={MyAccount}/>
...
<Route component={Error404}/>
</Switch>
</div>
</BrowserRouter>
);
}
}
我知道我可以使用this.props.location.pathname 通过子组件访问应用程序的当前路径位置,但我需要从父组件访问它,就在<BrowserRouter/> 的下方,以运行与子组件无关的附加逻辑成分。我怎样才能得到这个位置?
【问题讨论】: