(更新)V5.1 和 Hooks(需要 React >= 16.8)
您可以在组件中使用useHistory、useLocation 和useRouteMatch 来获取match、history 和location。
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 来在您的组件道具中注入match、history 和location。
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 来在组件道具中注入router、params、location、routes。
class Child extends React.Component {
render() {
const { router, params, location, routes } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
原答案
如果不想使用道具,可以使用React Router documentation中描述的上下文
首先,您必须设置您的childContextTypes 和getChildContext
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
}