web-dev-qa-db-ja.com

子コンポーネントでthis.props.locationを取得する反応ルーター

<Route path="/" component={App} />は、Applocationなどのparamsルーティング関連の小道具を提供します。 Appコンポーネントに多くのネストされた子コンポーネントがある場合、子コンポーネントにこれらの小道具にアクセスさせるにはどうすればいいですか:

  • アプリから小道具を渡す
  • ウィンドウオブジェクトを使用する
  • ネストされた子コンポーネントのルートを作成する

this.context.routerにはルートに関連する情報がいくつかあると思いましたが、this.context.routerにはルートを操作するためのいくつかの機能しかないようです。

52
xiaofan2406

(更新)V4&V5

コンポーネントの小道具で withRoutermatch および history を注入するために location HOCを使用できます。

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

withRouter を使用して、注入することができます routerparamslocationroutes =コンポーネントの小道具で。

class Child extends React.Component {

  render() {
    const { router, params, location, routes } = this.props

    return (
      <div>{location.pathname}</div>
    )
  }
}

export default withRouter(Child)

元の答え

小道具を使用したくない場合は、 React Router documentation で説明されているコンテキストを使用できます

まず、childContextTypesgetChildContextを設定する必要があります

class App extends React.Component{

  getChildContext() {
    return {
      location: this.props.location
    }
  }

  render() {
    return <Child/>;
  }
}

App.childContextTypes = {
    location: React.PropTypes.object
}

次に、次のようなコンテキストを使用して、子コンポーネントの場所オブジェクトにアクセスできます。

class Child extends React.Component{

   render() {
     return (
       <div>{this.context.location.pathname}</div>
     )
   }

}

Child.contextTypes = {
    location: React.PropTypes.object
 }
88
QoP