ReactJS-根据嵌套路由更改父级中的组件
我将我的应用程序包装在一个组件中,该组件呈现页眉、页脚和任何路由子组件 在/admin时,我试图将ReactJS-根据嵌套路由更改父级中的组件,reactjs,react-router,Reactjs,React Router,我将我的应用程序包装在一个组件中,该组件呈现页眉、页脚和任何路由子组件 在/admin时,我试图将组件替换为 路线 <Route path='/' component={SiteWrapper} > <IndexRoute component={Home} /> <Route path="admin" component={Admin}> <Route path="dashboard" component={Dashboard}/>
组件替换为
路线
<Route path='/' component={SiteWrapper} >
<IndexRoute component={Home} />
<Route path="admin" component={Admin}>
<Route path="dashboard" component={Dashboard}/>
</Route>
</Route>
站点包装器组件
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>
)
}
}
导出默认类SiteWrapper扩展React.Component{
render(){
返回(
//要替换为if on/admin吗
{this.props.children.props.route.header?:null}
{this.props.children}
)
}
}
为此,我认为您可以通过窗口.location
或this.props.location.pathname
检查路由,它将包含路由名称,如果路由名称为/admin
,则渲染头
组件,否则渲染头组件
这样写:
{ this.prop.location.pathname === '/admin'? <AdminHeader/>: <Header/>}
{this.prop.location.pathname=='/admin'?:}
您可以使用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>
)
}
}
导出默认类SiteWrapper扩展React.Component{
render(){
返回(
{(this.prop.location.pathname=='admin')?:}
{this.props.children.props.route.header?:null}
{this.props.children}
)
}
}
如果我们能做到这一点,那么为什么我们甚至需要来自react路由器的消息