¥Breadcrumbs Guide
在 Remix 中,你可以根据路由层次结构构建动态面包屑导航。本指南将指导你完成使用 useMatches
和 handle
功能的过程。
¥In Remix, you can build dynamic breadcrumbs based on your route hierarchy. This guide will take you through the process using the useMatches
and handle
features.
¥Understanding the Basics
Remix 提供对 React 元素树顶部所有路由匹配项及其相关数据的访问。这使得像 <Meta />
、<Links />
和 <Scripts />
这样的组件能够从嵌套路由中获取值并将其渲染到文档顶部。
¥Remix provides access to all route matches and related data at the top of the React element tree. This enables components like <Meta />
, <Links />
, and <Scripts />
to get values from nested routes and render them at the top of the document.
你可以使用 useMatches
和 handle
函数实现类似的策略。虽然我们专注于面包屑导航,但这里演示的原则适用于各种场景。
¥You can use a similar strategy using the useMatches
and handle
functions. While we're focusing on breadcrumbs, the principles demonstrated here are applicable to a range of scenarios.
¥Defining the Breadcrumbs for Routes
首先将 breadcrumb
属性添加到路由的 handle
中。此属性并非 Remix 独有 - 你可以随意命名。在我们的示例中,我们将其称为 breadcrumb
。
¥Start by adding a breadcrumb
attribute to your route's handle
. This attribute isn't specific to Remix – you can name it whatever you like. For our example, we'll call it breadcrumb
.
export const handle = {
breadcrumb: () => <Link to="/parent">Some Route</Link>,
};
同样,你可以为子路由定义面包屑导航:
¥Similarly, you can define breadcrumbs for child routes:
export const handle = {
breadcrumb: () => (
<Link to="/parent/child">Child Route</Link>
),
};
¥Aggregating Breadcrumbs in the Root Route
现在,使用 useMatches
将所有内容整合到你的根路由中:
¥Now, bring everything together in your root route using useMatches
:
import {
Links,
Scripts,
useLoaderData,
useMatches,
} from "@remix-run/react";
export default function Root() {
const matches = useMatches();
return (
<html lang="en">
<head>
<Links />
</head>
<body>
<header>
<ol>
{matches
.filter(
(match) =>
match.handle && match.handle.breadcrumb
)
.map((match, index) => (
<li key={index}>
{match.handle.breadcrumb(match)}
</li>
))}
</ol>
</header>
<Outlet />
</body>
</html>
);
}
请注意,我们将 match
对象传递给面包屑导航,这使我们能够利用 match.data
根据路由数据增强面包屑导航的内容。本示例未使用该功能,但你可能希望使用加载器数据中的值作为面包屑导航。
¥Note that we pass the match
object to breadcrumbs, allowing us to potentially utilize match.data
for enhancing breadcrumb content based on the route's data. This example doesn't use it, but you'll likely want to use values from your loader data for the breadcrumb.
将 useMatches
与 handle
结合使用,可以为路由提供一种强大的方法,使其能够参与元素树中高于其实际渲染点的渲染过程。
¥Using useMatches
with handle
offers a robust way for routes to contribute to rendering processes higher up the element tree than their actual render point.
¥Additional Resources