REACT ROUTER DOM 中的嵌套路由,在 Router 中包装组件
Nested Routes in REACT ROUTER DOM, wrapping Components in Router
我有 2 个组件,我想要一个组件在一些路由中通用,另一个组件在其余路由中通用。
在这两个组件中,我在两个组件中都使用了 {props.children} 用于嵌套路由。
我的代码是:
<Router history={history}>
<div className='routeContainer'>
<Switch>
<Component1>
<Route exact path='/' component={Dashboard} />
<Route exact path='/abc' component={ComponentAbc} />
</Component1>
<Component2>
<Route exact path='/def' component={ComponentDEF} />
<Route exact path='/xyz' component={ComponentXYZ} />
</Component2>
</Switch>
</div>
</Router>
在组件 1 和组件 2 中,我使用的是{this.props.children}
如下:
render () {
return (
<div>
<SideBar />
<Header />
{this.props.children}
</div>
)
}
这不起作用,请帮助使这个结构起作用。
"All children of a <Switch>
should be <Route>
or <Redirect>
elements.
Only the first child to match the current location will be rendered." - react-router
如果您想要路由组件的父级,您可以执行以下操作之一:
- 包裹内部组件
- 包裹在RouteProps - 组件
无论哪种方式,您都需要删除 <Switch>
中除 <Routes/>
或 <Redirects/>
之外的所有内容
替代示例 2:
<Route exact path='/' component={()=> (
<Component1>
<Dashboard />
</Component1>
)} />
我有 2 个组件,我想要一个组件在一些路由中通用,另一个组件在其余路由中通用。
在这两个组件中,我在两个组件中都使用了 {props.children} 用于嵌套路由。
我的代码是:
<Router history={history}>
<div className='routeContainer'>
<Switch>
<Component1>
<Route exact path='/' component={Dashboard} />
<Route exact path='/abc' component={ComponentAbc} />
</Component1>
<Component2>
<Route exact path='/def' component={ComponentDEF} />
<Route exact path='/xyz' component={ComponentXYZ} />
</Component2>
</Switch>
</div>
</Router>
在组件 1 和组件 2 中,我使用的是{this.props.children} 如下:
render () {
return (
<div>
<SideBar />
<Header />
{this.props.children}
</div>
)
}
这不起作用,请帮助使这个结构起作用。
"All children of a
<Switch>
should be<Route>
or<Redirect>
elements. Only the first child to match the current location will be rendered." - react-router
如果您想要路由组件的父级,您可以执行以下操作之一:
- 包裹内部组件
- 包裹在RouteProps - 组件
无论哪种方式,您都需要删除 <Switch>
<Routes/>
或 <Redirects/>
之外的所有内容
替代示例 2:
<Route exact path='/' component={()=> (
<Component1>
<Dashboard />
</Component1>
)} />