javascript - react-router中嵌套的子元件拿location物件的問題
仅有的幸福
仅有的幸福 2017-06-26 10:50:02
0
2
804

比如說一個頁面有個modal元件,modal元件裡面的內容寫在子元件裡面(ModalDetail),在這個元件裡面拿不到this.props.location,求解答,除了從父元件傳進去和通過window物件拿,還有什麼方法

仅有的幸福
仅有的幸福

全部回覆(2)
某草草

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之後,就可以存取到你想要的屬性了,你還可以進一步學習,看看裡面都有些什麼。

Ty80

也可以使用withRouter,透過this.props.location取得

import React, { Component } from 'react';
import { withRouter } from 'react-router'


class  MyComponent extends Component {

   .....
}

export default withRouter(MyComponent)
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!