For example, a page has a modal component. The content in the modal component is written in the subcomponent (ModalDetail). This.props.location cannot be obtained in this component. Please answer. In addition to passing it in from the parent component and passing it through Is there any other way to get the window object?
某草草2017-06-26 10:52:02
Versions before
react-router v4 had a higher-order component called withRouter
. You just need to wrap one layer when defining your own modal component.
The v4 version has not been used for the time being, and it is unclear whether there have been any changes
import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'
// A simple component that shows the pathname of the current location
class ShowTheLocation 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 (
<p>You are now at {location.pathname}</p>
)
}
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
export default withRouter(ShowTheLocation)
After wrapping a layer of withRouter, you can access the attributes you want. You can also study further to see what is inside.
PHP中文网2017-06-26 10:52:02
You can also use withRouter and get it through this.props.location
import React, { Component } from 'react';
import { withRouter } from 'react-router'
class MyComponent extends Component {
.....
}
export default withRouter(MyComponent)