我正在尝试弄清楚如何将 React Router 的 location prop 传递给组件。
我有一个这样定义的路线:
<Route
path="placeholder"
render={(props) => <Navigation {...props} />}
/>
在我的导航组件中,我在渲染方法中执行 console.log(this.props);
只是为了获得一个空对象。是什么赋予了? location 属性不是应该自动提供给路由内的任何组件吗?
顺便说一句,我使用的是 react-router-dom 版本 4.2.2
。
最佳答案
您需要使用 withRouter
包装您的组件为了在您的组件属性中注入(inject)match
、history
和location
。
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)
关于javascript - 如何将 React Router location prop 传递给组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51203629/