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

如何创建React Router v6的合法自定义路由子组件?

React Router v6 多路径路由复用方案

React Router v6 确实严格限制了<Routes>的直接子节点只能是<Route>、<React.Fragment>或者null,所以你自定义的<MultipleRoute>会被判定为非法子组件。不过可以通过以下方式实现多路径路由的复用:

方案一:封装返回Fragment的组件

写一个组件,接收路径数组和要渲染的元素,内部遍历生成多个<Route>并包裹在<React.Fragment>中:

import { Route } from 'react-router-dom';
import React from 'react';

const MultipleRoute = ({ paths, element }) => {
  return (
    <>
      {paths.map(path => (
        <Route key={path} path={path} element={element} />
      ))}
    </>
  );
};

使用方式:

<Routes>
  <MultipleRoute 
    paths={["/a-route", "/another-route", "/another-more", "/even-other"]}
    element={<VeryBigChildren>....</VeryBigChildren>}
  />
  {/* 其他路由 */}
</Routes>

方案二:直接在路由中渲染数组

如果不想额外封装组件,也可以直接在<Routes>里遍历路径数组生成<Route>:

const sharedPaths = ["/a-route", "/another-route", "/another-more", "/even-other"];

<Routes>
  {sharedPaths.map(path => (
    <Route key={path} path={path} element={<VeryBigChildren>....</VeryBigChildren>} />
  ))}
</Routes>

关键说明

  • React Router v6 会检查<Routes>的直接子节点类型,只有<Route>、<React.Fragment>(或短语法<>)能被正确识别,所以通过Fragment包裹生成的<Route>可以绕过这个限制。
  • 每个<Route>必须设置唯一的key,这里用路径本身作为key刚好满足唯一性要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 08:23:22