(更新)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注入
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
您可以使用
withRouterHOC以注入
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)
原始答案
如果您不想使用道具,可以使用React Router文档中所述的上下文
首先,你必须设置你的
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 }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)