createRoutesFromElements
createRoutesFromElements
是一个从 <Route>
元素创建路由对象的辅助函数。如果您更喜欢将路由创建为 JSX 而不是对象,它将非常有用。
import {
createBrowserRouter,
createRoutesFromElements,
RouterProvider,
Route,
} from "react-router-dom";
// You can do this:
const router = createBrowserRouter(
createRoutesFromElements(
<Route path="/" element={<Root />}>
<Route path="dashboard" element={<Dashboard />} />
<Route path="about" element={<About />} />
</Route>
)
);
// Instead of this:
const router = createBrowserRouter([
{
path: "/",
element: <Root />,
children: [
{
path: "dashboard",
element: <Dashboard />,
},
{
path: "about",
element: <About />,
},
],
},
]);
它也被 <Routes>
内部使用,以从其 <Route>
子元素生成路由对象。
declare function createRoutesFromElements(
children: React.ReactNode
): RouteObject[];
interface RouteObject {
caseSensitive?: boolean;
children?: RouteObject[];
element?: React.ReactNode;
index?: boolean;
path?: string;
}