gpt4 book ai didi

reactjs - react-router-dom:从 组件中获取 props.location

转载 作者:行者123 更新时间:2023-12-03 13:33:08 25 4
gpt4 key购买 nike

我有一个简单的应用程序,使用 BrowserRouter来自“react-router-dom”v4。我正在尝试访问 location.pathname <BrowserRouter/> 内的属性(property)组件,无济于事:

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/> 下面的父组件访问它运行与子组件无关的附加逻辑。我怎样才能获得这个位置?

最佳答案

您还可以使用 withRouter 来完成此操作这与将代码放入 render 具有类似的结果参数并避免需要“假”<Route/> .

本质上,您将需要知道位置的 JSX 放在它自己的组件中,该组件由 withRouter 包装。 。这为组件提供了位置:

import { withRouter } from 'react-router-dom';

const Content = withRouter(props =>
<div className={(props.location.pathname === "/account") ? "backg...
...
</div>
);

然后您在主路由器部分中使用它:

class App extends Component{
render() {
return (
<BrowserRouter>
<Content/>
...

关于reactjs - react-router-dom:从 <BrowserRouter> 组件中获取 props.location,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47298325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com