反应路由器 this.props.location [英] react router this.props.location

查看:30
本文介绍了反应路由器 this.props.location的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

希望得到您的帮助

解决方案

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

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

举个例子:

您的路由器配置:

<路由器><Route path="/" component={App}>//...</路由器

路由组件App:

class App 扩展 React.Component{//...使成为() {return }}

I need a help with react-router v2+ I have to change class of navbar when route changed for example for route /profile className will be "profile-header" I tried to use this.props.location in navbar component but it shows undefined

Hope your help

解决方案

Your navbar component (as you described it in your question) is probably not the route component, right? By route component I mean the one that you use in your react-router configuration that is loaded for a specific route.

this.props.location is accessible only on such route component, so you need to pass it down to your navbar.

Let's take an example:

Your router config:

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

Route component App:

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

这篇关于反应路由器 this.props.location的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆