在App组件中访问位置属性

时间:2018-03-08 18:28:21

标签: javascript reactjs react-router

有没有办法从我的App组件中的react路由器访问道具?我正在尝试访问this.props.locationBrowserRouter的{​​{1}}媒体资源,以便将其传递给App.js

index.js

HeaderContainer

App.js

function renderApp() {
    ReactDOM.render(
        <BrowserRouter>
            <App />
        </BrowserRouter>,
        document.getElementById('react-app')
    );
}
renderApp();

1 个答案:

答案 0 :(得分:1)

您需要使用withRouter HOC。

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 (
      <div>You are now at {location.pathname}</div>
    )
  }
}
export default withRouter(ShowTheLocation)

参考:https://reacttraining.com/react-router/web/api/withRouter