[英]react-router getting this.props.location in child components
據我了解<Route path="/" component={App} />
將提供與App
路由相關的道具,如location
和params
。 如果我的App
組件有許多嵌套的子組件,我如何讓子組件在沒有以下情況下訪問這些道具:
我以為this.context.router
會有一些與路由相關的信息,但是this.context.router
似乎只有一些操作路由的功能。
(更新) 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 來在你的組件 props 中注入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 來在你的組件 props 中注入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)
原答案
如果你不想使用 props,你可以使用React Router 文檔中描述的上下文
首先,您必須設置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
}
如果上述解決方案對您不起作用,您可以使用import { withRouter } from 'react-router-dom';
使用它,您可以將您的子類導出為 -
class MyApp extends Component{
// your code
}
export default withRouter(MyApp);
還有你的路由器課程 -
// your code
<Router>
...
<Route path="/myapp" component={MyApp} />
// or if you are sending additional fields
<Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.