(Actualización) V5.1 y Hooks (Requiere React> = 16.8)
Puede usar useHistory, useLocationy useRouteMatchen su componente para obtener match, historyy 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
(Actualización) V4 y V5
Puede utilizar withRouterhoc a fin de inyectar match, historyy locationen sus apoyos componentes.
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)
(Actualización) V3
Puede utilizar withRouterhoc a fin de inyectar router, params, location, routesen sus apoyos componentes.
class Child extends React.Component {
render() {
const { router, params, location, routes } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
Respuesta original
Si no desea usar los accesorios, puede usar el contexto como se describe en la documentación de React Router
Primero, tienes que configurar tu childContextTypesygetChildContext
class App extends React.Component{
getChildContext() {
return {
location: this.props.location
}
}
render() {
return <Child/>;
}
}
App.childContextTypes = {
location: React.PropTypes.object
}
Luego, podrá acceder al objeto de ubicación en sus componentes secundarios usando el contexto como este
class Child extends React.Component{
render() {
return (
<div>{this.context.location.pathname}</div>
)
}
}
Child.contextTypes = {
location: React.PropTypes.object
}