1. ホーム
  2. javascript

[解決済み] react-router 子コンポーネントでthis.props.locationを取得する。

2023-02-25 16:08:39

質問

私の理解では <Route path="/" component={App} />App のようなルーティング関連のプロップは locationparams . もし、私の App コンポーネントが多くのネストされた子コンポーネントを持つ場合、子コンポーネントがこれらのプロップにアクセスできるようにするにはどうすればよいでしょうか。

  • Appからpropsを渡す
  • ウィンドウオブジェクトの使用
  • ネストされた子コンポーネントのためのルートを作成する

私は this.context.router にはルートに関連する情報があると思ったのですが this.context.router はルートを操作するためのいくつかの関数しか持っていないようです。

どのように解決するのですか?

V6

以下のように useNavigate , useLocation そして useMatch を取得するために、コンポーネントに matchPath , navigate そして location .

const Child = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const match = useMatch("write-the-url-you-want-to-match-here");

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

export default Child

V5.1 フック (要React >= 16.8)

以下のように useHistory , useLocation そして useRouteMatch を取得するために、コンポーネントに match , history そして location .

const Child = () => {
  const location = useLocation();
  const history = useHistory();
  const match = useRouteMatch("write-the-url-you-want-to-match-here");

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

export default Child

V4 & V5

以下のように withRouter を注入するために HOC match , history そして location をコンポーネントプロパティで指定します。

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 を注入するために HOC router , params , location , routes をコンポーネントプロパティに追加してください。

class Child extends React.Component {

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

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

export default withRouter(Child)

オリジナルの回答

プロップスを使用したくない場合は、以下のようにコンテキストを使用することができます。 React Routerのドキュメント

まず最初に 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
 }