react-router在子组件中获取this.props.location
据我所知,<Route path="/" component={App}
/>将提供App与路由相关的道具,例如location和params。如果我的App组件有许多嵌套的子组件,那么我如何在不使用以下子项的情况下获取子组件:
- 从App传递道具
- 使用窗口对象
- 为嵌套的子组件创建路线
我以为this.context.router会有一些与路线有关的信息,但this.context.router似乎只有一些功能可以操纵路线。
回答:
您可以使用useHistory,useLocation并useRouteMatch在你的组件来获得match,history和location。
const Child = () => { const location = useLocation();
const history = useHistory();
const match = useRouteMatch("write-the-url-you-want-to-match-here");
return (
<div>{location.pathname}</div>
)
}
export default Child
您可以使用withRouter,以HOC注入match,history并location在组件的道具。
class Child extends React.Component { static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}
render() {
const { match, location, history } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
您可以使用withRouterHOC以注入router,params,location,routes在组件中的道具。
class Child extends React.Component { render() {
const { router, params, location, routes } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
如果您不想使用道具,可以使用React Router文档中所述的上下文
首先,你必须设置你的childContextTypes和getChildContext
class App extends React.Component{ getChildContext() {
return {
location: this.props.location
}
}
render() {
return <Child/>;
}
}
App.childContextTypes = {
location: React.PropTypes.object
}
然后,您将可以使用这样的上下文访问子组件中的location对象
class Child extends React.Component{ render() {
return (
<div>{this.context.location.pathname}</div>
)
}
}
Child.contextTypes = {
location: React.PropTypes.object
}
以上是 react-router在子组件中获取this.props.location 的全部内容, 来源链接: utcz.com/qa/433662.html

