2017-07-05 42 views
1

我需要访问父组件中的活动路径,以便根据位置改变一些CSS。这里是App - 父母:React路由器:获取容器组件中的位置

class App extends React.Component { 

    render(){ 
    return (
     <div className="wrapper" > 
     <div className="content"> 
      <Router> 
      <div className="container_b"> 
      <Menu /> 
      <div> 
       <Route exact path="/" component={Home}/> 
       <Route path="/confidence" component={ConfidenceInterval}/> 
       <Route path="/proind" component={ProportionTestInd}/> 
       <Route path="/prodep" component={ProportionTestDep}/> 
      </div> 
      </div> 
      </Router> 
      <div className="push"></div> 
     </div> 
     <footer className="footer"><Footer /></footer> 
     </div> 
    ) 
    } 

} 

回答

2

我认为对于App组件,您有两个选择。第一个是使用withRouter高阶组件封装App。 React-router提供了一个叫路由器的高阶组件,它将匹配,历史和位置道具传递给它所包裹的组件。 (详情请查看withRouter

在这种情况下,你可以到以下

class App extends React.Component { 

    render(){ 
    const {location: {pathname}} = this.props // pathname gives you the current path 
    return (
     <div className="wrapper" > 
     <div className="content"> 
      <Router> 
      <div className="container_b"> 
      <Menu /> 
      <div> 
       <Route exact path="/" component={Home}/> 
       <Route path="/confidence" component={ConfidenceInterval}/> 
       <Route path="/proind" component={ProportionTestInd}/> 
       <Route path="/prodep" component={ProportionTestDep}/> 
      </div> 
      </div> 
      </Router> 
      <div className="push"></div> 
     </div> 
     <footer className="footer"><Footer /></footer> 
     </div> 
    ) 
    } 

} 

export const WrappedApp = withRouter(App) 

第二个选项是,(再次应用程序组件),可以使用window.location的(请window.location)。 location.pathname在这种情况下也应该给你当前的路径。

对于其他组件,例如Home,ConfidenceInterval等,Route默认会传递匹配,历史和位置道具,以便您可以使用它们。

+0

window.location确实可行,但问题在于render()仅调用一次,并非每次页面更改时都不能使用。不管怎么说,还是要谢谢你 – eli