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:
- 使用窗口对象从App
- 传递道具
- 为嵌套子组件创建路径
我认为 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.
推荐答案
(更新)V4
您可以使用 withRouter
HOC为了注入 匹配
, 历史记录
和 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
你的组件道具。
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 Router文档
If you don't want to use the props, you can use the context as described in React Router documentation
首先,您必须设置 childContextTypes
和 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屋!