据我所知,<Route path="/" component={App} />将提供App与路由相关的道具,例如location和params。如果我的App组件有许多嵌套的子组件,那么我如何在不使用以下子项的情况下获取子组件:
<Route path="/" component={App} />
App
location
params
我以为this.context.router会有一些与路线有关的信息,但this.context.router似乎只有一些功能可以操纵路线。
this.context.router
(更新)V5.1和Hooks(需要React > = 16.8)
您可以使用useHistory,useLocation并useRouteMatch在你的组件来获得match,history和location。
useHistory
useLocation
useRouteMatch
match
history
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在组件的道具。
withRouter
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
您可以使用withRouterHOC以注入router,params,location,routes在组件中的道具。
router
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
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 }