(अपडेट) V5.1 और हुक (प्रतिक्रिया की आवश्यकता है = = 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इंजेक्षन करने के लिए match, historyऔर locationअपने घटक सहारा में HOC का उपयोग कर सकते हैं ।
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इंजेक्षन करने के लिए अस्थायी 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)
मूल उत्तर
यदि आप प्रॉपर का उपयोग नहीं करना चाहते हैं, तो आप संदर्भ का उपयोग कर सकते हैं जैसा कि रिएक्ट राउटर प्रलेखन में वर्णित है
सबसे पहले, आपको अपना 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
}