ReactJS - 根据嵌套路由更改父组件中的组件
ReactJS - Change Component in parent depending on nested route
我将我的应用程序包装在一个组件中,该组件呈现页眉、页脚和任何路由的子组件。
我在 /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.location
或 this.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>
)
}
}
我将我的应用程序包装在一个组件中,该组件呈现页眉、页脚和任何路由的子组件。
我在 /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.location
或 this.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>
)
}
}