Utilities

插槽

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

Features

    可以用来支持您自己的 `asChild` 属性。

安装

从命令行安装组件。

npm install @radix-ui/react-slot

解剖结构

导入组件。

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>
);
}

用法

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>
);