小编典典

react-router-dom:从内部获取props.location 零件

reactjs

我有一个简单的应用程序,它BrowserRouter从“ react-router-dom”
v4使用。我试图location.pathname<BrowserRouter/>组件内部访问属性,但无济于事:

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/>以运行与子组件无关的其他逻辑。如何获得此位置?


阅读 794

收藏
2020-07-22

共1个答案

小编典典

您也可以使用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/>
                ...
2020-07-22