簡體   English   中英

ReactJS-根據嵌套路線更改父級中的組件

[英]ReactJS - Change Component in parent depending on nested route

我的應用程序包裝在一個組件中,該組件呈現Header,Footer和所有路由的子組件。

在/ admin時,我試圖用</HeaderAdmin/>替換<Header />組件。

路線

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

SiteWrapper比較

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>
        )
    }
}

為此,我認為您可以通過window.locationthis.props.location.pathname檢查路由,其中​​將包含路由名稱,如果路由名稱為/admin則呈現Header組件,否則render AdminHeader組件。

像這樣寫:

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

您可以使用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>
        )
    }
}

暫無
暫無

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

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