react-router中嵌套的子组件拿location对象的问题

比如说一个页面有个modal组件,modal组件里面的内容写在子组件里面(ModalDetail),在这个组件里面拿不到this.props.location,求解答,除了从父组件传进去和通过window对象拿,还有什么方法

一只萌萌小番薯
浏览 1134回答 1
1回答

红糖糍粑

react-router v4之前的版本,有一个叫做withRouter的高阶组件。你在定义自己的modal组件时包一层即可。v4版本暂时没有用过,有没有改动不清楚import React from 'react'import PropTypes from 'prop-types'import { withRouter } from 'react-router'// A simple component that shows the pathname of the current locationclass ShowTheLocation extends React.Component {&nbsp; static propTypes = {&nbsp; &nbsp; match: PropTypes.object.isRequired,&nbsp; &nbsp; location: PropTypes.object.isRequired,&nbsp; &nbsp; history: PropTypes.object.isRequired&nbsp; }&nbsp; render() {&nbsp; &nbsp; const { match, location, history } = this.props&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>You are now at {location.pathname}</div>&nbsp; &nbsp; )&nbsp; }}// Create a new component that is "connected" (to borrow redux// terminology) to the router.export default withRouter(ShowTheLocation)包一层withRouter之后,就可以访问到你想要的属性了,你还可以进一步学习,看看里面都有些什么。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript