react-router 在子组件中获取 this.props.location [英] react-router getting this.props.location in child components
问题描述
据我所知 <Route path="/" component={App}/>
将提供 App
路由相关的道具,如 location
和 params
.如果我的 App
组件有很多嵌套的子组件,我如何让子组件在没有:
As I understand <Route path="/" component={App} />
will gives App
routing-related props like location
and params
. If my App
component has many nested child components, how do I get the child component to have access to these props without:
- 从应用程序传递道具
- 使用窗口对象
- 为嵌套子组件创建路由
我以为 this.context.router
会有一些与路由相关的信息,但是 this.context.router
似乎只有一些操作路由的功能.
I thought this.context.router
would have some information related to the routes, but this.context.router
seems to only have some functions to manipulate the routes.
推荐答案
(Update) V5.1 &钩子(需要 React >= 16.8)
您可以使用 useHistory
,useLocation
和 useRouteMatch
在您的组件中获取 match
, history
和 location
.
You can use useHistory
, useLocation
and useRouteMatch
in your component to get match
, history
and 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
(更新)V4 &V5
您可以按顺序使用 withRouter
HOC注入 match
, history
和 location
在您的组件道具中.
You can use withRouter
HOC in order to inject match
, history
and location
in your component props.
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)
(更新)V3
您可以使用 withRouter
HOC 以注入 router
, params
, location
, routes
在你的组件 props 中.
You can use withRouter
HOC in order to inject router
, params
, location
, routes
in your component props.
class Child extends React.Component {
render() {
const { router, params, location, routes } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
原答案
如果不想使用道具,可以使用React 路由器文档
If you don't want to use the props, you can use the context as described in React Router documentation
首先,你必须设置你的 childContextTypes
和 getChildContext
First, you have to set up your childContextTypes
and getChildContext
class App extends React.Component{
getChildContext() {
return {
location: this.props.location
}
}
render() {
return <Child/>;
}
}
App.childContextTypes = {
location: React.PropTypes.object
}
然后,您将能够使用这样的上下文访问子组件中的位置对象
Then, you will be able to access to the location object in your child components using the context like this
class Child extends React.Component{
render() {
return (
<div>{this.context.location.pathname}</div>
)
}
}
Child.contextTypes = {
location: React.PropTypes.object
}
这篇关于react-router 在子组件中获取 this.props.location的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!