据我所知,<Route path="/" component={App} />
将提供App
个路由相关props ,比如location
和params
.如果我的App
组件有许多嵌套的子组件,我如何让子组件能够访问这些props ,而不必:
- 从应用程序传递props
- 使用窗口对象
- 为嵌套子零部件创建管线
我以为this.context.router
会有一些与路由相关的信息,但this.context.router
似乎只有一些操作路由的功能.
据我所知,<Route path="/" component={App} />
将提供App
个路由相关props ,比如location
和params
.如果我的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 (Requires 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)
Original answer
如果你不想使用props ,可以使用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
}
然后,您将能够使用如下上下文访问子组件中的location对象
class Child extends React.Component{
render() {
return (
<div>{this.context.location.pathname}</div>
)
}
}
Child.contextTypes = {
location: React.PropTypes.object
}