据我了解<Route path="/" component={App} />
将给出 App
与路由相关的 Prop ,如 location
和 params
.如果我的App
组件有许多嵌套的子组件,我如何让子组件访问这些 Prop 而不需要:
- 从 App 传递 props
- 使用窗口对象
- 为嵌套的子组件创建路由
我以为this.context.router
会有一些与路线相关的信息,但是this.context.router
似乎只有一些操作路线的功能。
最佳答案
V6
您可以使用 useNavigate
, useLocation
和 useMatch
在您的组件中获取 matchPath
, navigate
和 location
.
const Child = () => {
const location = useLocation();
const navigate = useNavigate();
const match = useMatch("write-the-url-you-want-to-match-here");
return (
<div>{location.pathname}</div>
)
}
export default Child
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为了注入(inject)match
, history
和 location
在你的组件 Prop 中。
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为了注入(inject)router
, params
, location
, routes
在你的组件 Prop 中。
class Child extends React.Component {
render() {
const { router, params, location, routes } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
原始答案
如果不想使用 Prop ,可以使用 React Router documentation 中描述的上下文
首先,您必须设置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
}
关于javascript - react-router 在子组件中获取 this.props.location,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37516919/