比如說一個頁面有個modal元件,modal元件裡面的內容寫在子元件裡面(ModalDetail),在這個元件裡面拿不到this.props.location,求解答,除了從父元件傳進去和通過window物件拿,還有什麼方法
某草草2017-06-26 10:52:02
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 location
class ShowTheLocation 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 (
<p>You are now at {location.pathname}</p>
)
}
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
export default withRouter(ShowTheLocation)
包一層withRouter之後,就可以存取到你想要的屬性了,你還可以進一步學習,看看裡面都有些什麼。
PHP中文网2017-06-26 10:52:02
也可以使用withRouter,透過this.props.location取得
import React, { Component } from 'react';
import { withRouter } from 'react-router'
class MyComponent extends Component {
.....
}
export default withRouter(MyComponent)