cel*_*ade 6 reactjs react-router
我想知道如何从我用来定义路线的组件中获取当前位置.例如,我有一个名为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>
);
}
};
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试this.props.location.pathname像在其他组件中那样访问时,它会返回undefined.
在我需要使用的其他组件上withRouter,以便能够访问location信息.但我不能将它与Routes组件一起使用,因为它会引发错误.
我实际上并不需要pathname,我只想查看用户的路线,因为我在访问特定页面时会呈现不同的标题内容.
将标头换成<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>
);
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2893 次 |
| 最近记录: |