react-router-dom:从 <BrowserRouter> 中获取 props.location成分 [英] react-router-dom: getting props.location from within <BrowserRouter> component
问题描述
我有一个简单的应用程序,它使用来自react-router-dom"v4 的 BrowserRouter
.我试图从 <BrowserRouter/>
组件中访问 location.pathname
属性,但无济于事:
class App 扩展组件{使成为(){返回 (<浏览器路由器>//如何访问 this.props.location?<div className={(this.props.location.pathnme === "/account") ?"bgnd-black" : "bgnd-white"} ><开关><Route path="/login" component={LoginPage}/><Route path="/success" component={LoginSuccess}/><Route path="/account" component={MyAccount}/>...<路由组件={Error404}/></开关>
</BrowserRouter>);}}
我知道我可以通过带有 this.props.location.pathname
的子组件访问应用程序的当前路径位置,但是我需要从父组件访问它,就在 下方<BrowserRouter/>
运行与子组件无关的附加逻辑.我怎样才能得到这个位置?
您也可以使用 withRouter
来实现,这与将代码放入 render
的结果类似参数并避免需要假"
.
本质上,您将需要知道位置的 JSX 放在自己的组件中,该组件由 withRouter
包装.这提供了组件的位置:
import { withRouter } from 'react-router-dom';const Content = withRouter(props =><div className={(props.location.pathname === "/account") ?背......
);
然后在主路由器部分使用它:
class App 扩展组件{使成为() {返回 (<浏览器路由器><内容/>...
I have a simple App that uses BrowserRouter
from 'react-router-dom' v4. I'm trying to access the location.pathname
property from within the <BrowserRouter/>
component, without avail:
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>
);
}
}
I know that I can access the app's current path location through the child components with this.props.location.pathname
, but I need to access it from the parent component, just below <BrowserRouter/>
to run additional logic that doesn't pertain to child components. How can I get this location?
You can also do it using withRouter
which has a similar result to putting the code in a render
parameter and avoids the need for a "fake" <Route/>
.
Essentially you put the JSX that needs to know the location in a component of its own, which is wrapped by withRouter
. This supplies the location to the component:
import { withRouter } from 'react-router-dom';
const Content = withRouter(props =>
<div className={(props.location.pathname === "/account") ? "backg...
...
</div>
);
Then you use that in your main router section:
class App extends Component{
render() {
return (
<BrowserRouter>
<Content/>
...
这篇关于react-router-dom:从 <BrowserRouter> 中获取 props.location成分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!