如何将React Router位置道具传递给组件? [英] How to pass the React Router location prop to a component?

查看:113
本文介绍了如何将React Router位置道具传递给组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何将React Router的位置信息传递给组件。

I'm trying to figure out how to pass React Router's location prop to a component.

我有一条这样定义的路由:

I have a route defined like so:

<Route
  path="placeholder"
  render={(props) => <Navigation {...props} />}
/>

在我的导航组件中,我执行 console.log(this.props); 在render方法中只能获取一个空对象。是什么赋予了?

In my Navigation component I do console.log(this.props); in the render method only to get an empty object. What gives? Isn't the location prop supposed to be automatically supplied to any component inside a Route?

顺便说一句,我使用的是react-router-dom版本 4.2.2

By the way, I'm using react-router-dom version 4.2.2.

推荐答案

您需要使用 withRouter 以便注入 match 历史位置在组件道具中。

You need to wrap your component with withRouter in order to inject match, history and location in your component props.

import { withRouter } from 'react-router-dom';
class Navigation extends React.Component {

  render() {
    const { match, location, history } = this.props
    return (
      <div>{location.pathname}</div>
    )
  }
}

export default withRouter(Navigation)

这篇关于如何将React Router位置道具传递给组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆