自定义意图组件
如果有许多同类目标,可以包装一次 useIntentTarget,然后重复使用生成的组件。
可复用的 IntentButton
它接收普通按钮属性以及 onIntent、importance 和 cost。
"use client";
import type { ButtonHTMLAttributes } from "react";
import {
useIntentTarget,
type UseIntentTargetOptions,
} from "intent-link";
type IntentButtonProps =
ButtonHTMLAttributes<HTMLButtonElement> &
UseIntentTargetOptions;
export function IntentButton({
onIntent,
importance,
cost,
children,
...buttonProps
}: IntentButtonProps) {
const intentRef = useIntentTarget<HTMLButtonElement>({
onIntent,
importance,
cost,
});
return (
<button ref={intentRef} {...buttonProps}>
{children}
</button>
);
}用法
<IntentButton
className="preview-button"
onIntent={preloadPreview}
>
Preview
</IntentButton>可复用的 IntentArticle
同样的模式也适用于商品卡片或其他语义容器。
"use client";
import type { HTMLAttributes } from "react";
import {
useIntentTarget,
type UseIntentTargetOptions,
} from "intent-link";
type IntentArticleProps =
HTMLAttributes<HTMLElement> &
UseIntentTargetOptions;
export function IntentArticle({
onIntent,
importance,
cost,
children,
...articleProps
}: IntentArticleProps) {
const intentRef = useIntentTarget<HTMLElement>({
onIntent,
importance,
cost,
});
return (
<article ref={intentRef} {...articleProps}>
{children}
</article>
);
}用法
<IntentArticle
className="product-card"
onIntent={() => preloadProduct(productId)}
>
<ProductImage />
<ProductDetails />
</IntentArticle>