繁体   English   中英

反应路由器 this.props.location

[英]react router this.props.location

我需要 react-router v2+ 的帮助我必须在路由更改时更改导航栏的类,例如route /profile className将是"profile-header"我尝试在导航栏组件中使用this.props.location但它显示undefined

希望你的帮助

您的navbar组件(如您在问题中所描述的)可能不是路由组件,对吗? 我所说的route component是指您在为特定路由加载的react-router配置中使用的route component

this.props.location只能在这样的route component上访问,所以你需要把它传递给你的navbar

让我们举个例子:

您的路由器配置:

<Router>
    <Route path="/" component={App}>
    // ...
</Router

路由组件App

class App extends React.Component{
  // ...
  render() {
    return <Navbar location={this.props.location}/>
  }
}

在某些情况下,您可能无法访问 props.location 以传递给导航组件。

举个例子 - 我们的项目中有一个 header 组件,它包含在路由开关中,使其可用于所有路由。

<Switch>
  <Fragment>
    <Header/>
    <Route path='..' component={...}/>
    <Route path='..' component={...}/>
  </Fragment>
</Switch>

在上述场景中,无法将位置数据传递给 Header 组件。

当您的路由器未呈现组件时,更好的解决方案是使用 withRouter HOC。 当您将它包装在 withRouter HOC 中时,您仍然可以访问路由器属性历史记录、匹配和位置:

import { withRouter } from 'react-router-dom'
.... 
....
export default withRouter(ThisComponent)

反应路由器 v4

文档

  1. 当您有一个现有组件时,应该使用<Route> component属性。 <Route> render属性采用内联函数,该函数返回 html。

  2. 没有path <Route>将始终匹配。

基于此,我们可以为您的 html 结构的任何级别制作一个<Route>包装器。 它将始终显示并可以访问位置对象。

根据您的要求,如果用户访问/profile页面, <header>将具有profile-header类名称。

<Router>
    <Route render={({ location }) =>
        <header className={location.pathname.replace(/\//g, '') + '-header'}>
            // header content...
        </header>

        <div id="content"></div>

        <footer></footer>
    } />
</Router>

我无法使用此处给出的解决方案解决它,这对我有用:

我将history导入到我的组件中,并将history.location.pathname分配给一个变量,我后来将其用于动态样式操作。

如果您使用预定义的 location.state 值渲染组件,请首先使用 props.location.state 设置您的状态,然后在您的元素中使用您的状态数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM