You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Router v6中为Route创建自定义RouteWrapper并解决报错

报错原因

React Router v6 对 <Routes> 的直接子元素做了严格校验,只有 <Route> 或者 <React.Fragment> 可以作为它的直接子节点。你自定义的 RouteWrapper 哪怕内部返回的是 <Route>,组件本身不符合校验规则,就会触发报错,用 Fragment 包裹也没用,因为 Fragment 包裹后的直接子元素还是自定义的 RouteWrapper,不是 <Route>。


解决方案1:把自定义逻辑移到element属性层(最常用)

不要封装整个<Route>,而是封装要传递给element的组件部分,<Route>直接写在<Routes>内部:

// 封装布局+页面的组合逻辑
const RouteWrapper = ({ component: Component, layout: Layout, ...rest }) => {
  // 这里可以加自定义逻辑,比如权限校验、额外props传递等
  return (
    <Layout {...rest}>
      <Component />
    </Layout>
  )
}

// 使用处直接写原生Route
return (
  <Layout {...layoutProps} onAnimationEnd={onAnimationEnd} isInTransitionStage={isInTransitionStage}>
    <Routes location={displayLocation}>
      <Route 
        path='/' 
        element={
          <RouteWrapper 
            component={HomePage} 
            layout={MainLayout} 
            setLayout={setLayout}
            setLayoutProps={setLayoutProps}
          />
        } 
      />
      {/* 其他路由直接复用逻辑 */}
      <Route 
        path='/about' 
        element={
          <RouteWrapper 
            component={AboutPage} 
            layout={OtherLayout} 
          />
        } 
      />
    </Routes>
  </Layout>
);

解决方案2:批量生成Route配置(适合路由较多的场景)

如果需要批量生成路由,可以把自定义的路由配置项提前处理,遍历生成原生的<Route>组件:

// 提前定义路由配置
const routeConfig = [
  {
    path: '/',
    component: HomePage,
    layout: MainLayout,
    setLayout: setLayout,
    setLayoutProps: setLayoutProps
  },
  {
    path: '/about',
    component: AboutPage,
    layout: OtherLayout
  }
]

// 遍历生成原生Route
return (
  <Layout {...layoutProps} onAnimationEnd={onAnimationEnd} isInTransitionStage={isInTransitionStage}>
    <Routes location={displayLocation}>
      {routeConfig.map(route => (
        <Route 
          key={route.path}
          path={route.path}
          element={
            <route.layout {...route}>
              <route.component />
            </route.layout>
          }
        />
      ))}
    </Routes>
  </Layout>
);

内容的提问来源于stack exchange,提问作者EshgheCode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 05:24:04