我试图弄清楚如何将 React Router 的 location 属性传递给组件。
我有一个这样定义的路线:
<Route
path="placeholder"
render={(props) => <Navigation {...props} />}
/>
在我的导航组件中我这样做console.log(this.props);
在render方法中只得到一个空对象。是什么赋予了? location prop 不是应该自动提供给 Route 内的任何组件吗?
顺便说一下,我使用的是react-router-dom版本4.2.2
.
您需要用以下内容包装您的组件withRouter https://reacttraining.com/react-router/web/api/withRouter为了注入match
, history
and 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)