文档案例研究博客简中文档
Utilities

插槽

将其属性合并到其直接子元素上。

Features

  • 可用于支持您自己的 `asChild` 属性。

解剖结构

导入组件。

import { Slot } from "radix-ui";
export default () => (
<Slot.Root>
<div>你好</div>
</Slot.Root>
);

基本示例

用于创建您自己的 asChild API。

当您的组件有一个子元素时:

// your-button.jsx
import * as React from "react";
import { Slot } from "radix-ui";
function Button({ asChild, ...props }) {
const Comp = asChild ? Slot.Root : "button";
return <Comp {...props} />;
}

当您的组件有多个子元素时使用 Slottable 将属性传递给正确的元素:

// your-button.jsx
import * as React from "react";
import { Slot } from "radix-ui";
function Button({ asChild, children, leftElement, rightElement, ...props }) {
const Comp = asChild ? Slot.Root : "button";
return (
<Comp {...props}>
{leftElement}
<Slot.Slottable>{children}</Slot.Slottable>
{rightElement}
</Comp>
);
}

包装插槽元素

通过 child 属性将子元素传递给 Slottable,并提供一个渲染函数,以便将插槽元素包装在额外的标记中,同时 Slot 仍会将其属性和 refs 合并到子元素上。

// your-button.jsx
import * as React from "react";
import { Slot } from "radix-ui";
function Button({ asChild, children, ...props }) {
const Comp = asChild ? Slot.Root : "button";
return (
<Comp {...props}>
<Slot.Slottable child={children}>
{(child) => <span className="ButtonInner">{child}</span>}
</Slot.Slottable>
</Comp>
);
}

用法

import { Button } from "./your-button";
export default () => (
<Button asChild>
<a href="/contact">联系</a>
</Button>
);

事件处理程序

任何以 on 开头的属性(例如,onClick)都被视为事件处理程序。

在合并事件处理程序时,Slot 将创建一个新函数,其中子处理程序优先于插槽处理程序。

如果其中一个事件处理程序依赖于 event.defaultPrevented,请确保顺序正确。

import { Slot } from "radix-ui";
export default () => (
<Slot.Root onClick={(event) => { if (!event.defaultPrevented) console.log("未记录,因为默认被阻止。"); }} >
<button onClick={(event) => event.preventDefault()} />
</Slot.Root>
);

类型化插槽

Slot.createSlot 返回一个作用域限定为您传入的名称的 Slot 组件,该名称用于其错误消息。它接受类型参数,以指定插槽渲染的元素及其接受的属性,从而让使用者获得准确的类型。Slot.SlotProps 接受相同的类型参数。

import * as React from "react";
import { Slot } from "radix-ui";
type ButtonProps = React.ComponentPropsWithoutRef<"button"> & {
variant?: "solid" | "ghost";
};
const ButtonSlot = Slot.createSlot<HTMLButtonElement, ButtonProps>(
"Button.Slot",
);