您可以使用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
您可以使用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)
您可以使用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文档中所述的上下文
首先,你必须设置你的childContextTypes
和getChildContext
class App extends React.Component{
getChildContext() {
return {
location: this.props.location
}
}
render() {
return <Child/>;
}
}
App.childContextTypes = {
location: React.PropTypes.object
}
然后,您将可以使用这样的上下文访问子组件中的location对象
class Child extends React.Component{
render() {
return (
<div>{this.context.location.pathname}</div>
)
}
}
Child.contextTypes = {
location: React.PropTypes.object
}