reactjs – React路由器获取主路由器组件上的当前位置
发布时间:2020-12-15 20:11:22 所属栏目:百科 来源:网络整理
导读:我想知道如何从我用来定义路线的组件中获取当前位置.例如,我有一个名为Routes的组件,它包含所有路由,如下所示: class Routes extends React.Component { render() { return ( Router Nav / header{customHeader}/header Switch Route exact path="/" compon
我想知道如何从我用来定义路线的组件中获取当前位置.例如,我有一个名为Routes的组件,它包含所有路由,如下所示:
class Routes extends React.Component { render() { return ( <Router> <Nav /> <header>{customHeader}</header> <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> // Other routes </Switch> </Router> ); } }; 但是,当我尝试像在其他组件中一样访问this.props.location.pathname时,它返回undefined. 在其他组件上我需要使用withRouter以便能够访问位置信息.但是我不能将它与Routes组件一起使用,因为它会引发错误. 我实际上并不需要路径名,我只想查看用户的路由,因为我在访问特定页面时会呈现不同的标题内容. 解决方法
将标题包裹在< Route>中总是呈现.然后你可以通过道具访问所有东西.
class Routes extends React.Component { render() { return ( <Router> <Nav /> <Route render={(props) => { console.log(props.location) return ( <header>{customHeader}</header> ) }} /> <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> // Other routes </Switch> </Router> ); } }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |