簡體   English   中英

react-router 在子組件中獲取 this.props.location

[英]react-router getting this.props.location in child components

據我了解<Route path="/" component={App} />將提供與App路由相關的道具,如locationparams 如果我的App組件有許多嵌套的子組件,我如何讓子組件在沒有以下情況下訪問這些道具:

  • 從 App 傳遞道具
  • 使用窗口對象
  • 為嵌套子組件創建路由

我以為this.context.router會有一些與路由相關的信息,但是this.context.router似乎只有一些操作路由的功能。

(更新) V5.1 & Hooks (需要 React >= 16.8)

您可以在組件中使用useHistoryuseLocationuseRouteMatch來獲取matchhistorylocation

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 來在你的組件 props 中注入matchhistorylocation

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 來在你的組件 props 中注入routerparamslocationroutes

class Child extends React.Component {

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

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

export default withRouter(Child)

原答案

如果你不想使用 props,你可以使用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
 }

如果上述解決方案對您不起作用,您可以使用import { withRouter } from 'react-router-dom';


使用它,您可以將您的子類導出為 -

class MyApp extends Component{
    // your code
}

export default withRouter(MyApp);

還有你的路由器課程 -

// your code
<Router>
      ...
      <Route path="/myapp" component={MyApp} />
      // or if you are sending additional fields
      <Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM