小编典典

react-router在子组件中获取this.props.location

reactjs

据我所知,<Route path="/" component={App} />将提供App与路由相关的道具,例如locationparams。如果我的App组件有许多嵌套的子组件,那么我如何在不使用以下子项的情况下获取子组件:

  • 从App传递道具
  • 使用窗口对象
  • 为嵌套的子组件创建路线

我以为this.context.router会有一些与路线有关的信息,但this.context.router似乎只有一些功能可以操纵路线。


阅读 1417

收藏
2020-07-22

共1个答案

小编典典

(更新)V5.1和Hooks(需要React > = 16.8)

您可以使用useHistoryuseLocationuseRouteMatch在你的组件来获得matchhistorylocation

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注入matchhistorylocation在组件的道具。

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以注入routerparamslocationroutes在组件中的道具。

class Child extends React.Component {

  render() {
    const { router, params, location, routes } = this.props

    return (
      <div>{location.pathname}</div>
    )
  }
}

export default withRouter(Child)

原始答案

如果您不想使用道具,可以使用React Router文档中所述的上下文

首先,你必须设置你的childContextTypesgetChildContext

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
 }
2020-07-22