react-router-dom: getting props.location from within component

前端 未结 4 1281
野的像风
野的像风 2021-02-20 14:03

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 &l

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-20 14:26

    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" .

    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 =>
        
    );

    Then you use that in your main router section:

    class App extends Component{
        render() {
            return (
                
                    
                    ...
    

提交回复
热议问题