如何将React Router位置道具传递给组件? [英] How to pass the React Router location prop to a component?
问题描述
我试图弄清楚如何将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屋!