您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

您可以使用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

您可以使用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)

您可以使用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
 }
其他 2022/1/1 18:22:37 有425人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶