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

标签 javascript reactjs react-router

据我了解<Route path="/" component={App} />将给出 App与路由相关的 Prop ,如 locationparams .如果我的App组件有许多嵌套的子组件,我如何让子组件访问这些 Prop 而不需要:

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

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

最佳答案

V6

您可以使用 useNavigate , useLocationuseMatch在您的组件中获取 matchPath , navigatelocation .

const Child = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const match = useMatch("write-the-url-you-want-to-match-here");

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

export default Child

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

您可以使用 useHistory , useLocationuseRouteMatch在您的组件中获取 match , historylocation .

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为了注入(inject)match , historylocation在你的组件 Prop 中。

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为了注入(inject)router , params , location , routes在你的组件 Prop 中。

class Child extends React.Component {

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

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

export default withRouter(Child)

原始答案

如果不想使用 Prop ,可以使用 React Router documentation 中描述的上下文

首先,您必须设置childContextTypesgetChildContext

class App extends React.Component{
  
  getChildContext() {
    return {
      location: this.props.location
    }
  }

  render() {
    return <Child/>;
  }
}

App.childContextTypes = {
    location: React.PropTypes.object
}

然后,您将能够使用这样的上下文访问子组件中的位置对象

class Child extends React.Component{
   
   render() {
     return (
       <div>{this.context.location.pathname}</div>
     )
   }
   
}

Child.contextTypes = {
    location: React.PropTypes.object
 }

关于javascript - react-router 在子组件中获取 this.props.location,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37516919/

相关文章:

javascript - Yii 和 Javascript 表单提交

javascript - 异步 redux 函数如何工作?

javascript - react 路由器|仅在页面刷新时加载组件

javascript - CRA 和捆绑加载程序

javascript - 通过 map 标记导航到react-router URL

reactjs - 如何在 React Router v4 中嵌套路由?

javascript - jquery弹出窗口问题

javascript - CSS 3D 变换

javascript - 帖子表 react

javascript - 如何在 D3 中从 CSV 切换到 JSON? Github 类似图表