ReactJS - 根据嵌套路由更改父级中的组件

时间:2017-04-01 11:43:03

标签: reactjs react-router

我的应用程序包含在一个组件中,该组件呈现了页眉,页脚和任何路由的子组件。

我在/ admin时尝试用<Header />替换</HeaderAdmin/>组件。

路线

<Route path='/' component={SiteWrapper} >
  <IndexRoute component={Home} />
  <Route path="admin" component={Admin}>
    <Route path="dashboard" component={Dashboard}/>
  </Route>      
</Route>

SiteWrapper Comp

export default class SiteWrapper extends React.Component {
    render() {
        return (
            <div>
                <Header/> // Want to replace with <AdminHeader /> if on /admin
                <div className="container">
                    {this.props.children.props.route.header ? <PageHeader header={this.props.children.props.route.header} /> : null}
                    {this.props.children}
                </div>
                <Footer/>
            </div>
        )
    }
}

2 个答案:

答案 0 :(得分:1)

为此,我认为您可以通过window.locationthis.props.location.pathname检查路线,它将包含路线名称,如果路线名称为/admin则呈现Header }组件否则render AdminHeader组件。

像这样写:

{ this.prop.location.pathname === '/admin'? <AdminHeader/>: <Header/>} 

答案 1 :(得分:1)

您可以使用this.props.location.pathname查找路线名称

export default class SiteWrapper extends React.Component {
    render() {
        return (
            <div>
                {(this.prop.location.pathname === 'admin')? <AdminHeader/>: <Header/>} 
                <div className="container">
                    {this.props.children.props.route.header ? <PageHeader header={this.props.children.props.route.header} /> : null}
                    {this.props.children}
                </div>
                <Footer/>
            </div>
        )
    }
}
相关问题