Utilities

插槽

¥Slot

将其属性合并到其直接子项中。

Features

    Can be used to support your own `asChild` prop.

安装

¥Installation

从命令行安装组件。

¥Install the component from your command line.

npm install @radix-ui/react-slot

结构

¥Anatomy

导入组件。

¥Import the component.

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

基本示例

¥Basic example

用于创建你自己的 asChild API。

¥Use to create your own asChild API.

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

¥When your component has a single children element:

// 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 将 props 传递给正确的元素:

¥Use Slottable when your component has multiple children to pass the props to the correct element:

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

用法

¥Usage

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

事件处理程序

¥Event handlers

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

¥Any prop that starts with on (e.g., onClick) is considered an event handler.

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

¥When merging event handlers, Slot will create a new function where the child handler takes precedence over the slot handler.

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

¥If one of the event handlers relies on event.defaultPrevented make sure that the order is correct.

import { Slot } from "radix-ui";
export default () => (
<Slot.Root onClick={(event) => { if (!event.defaultPrevented) console.log("Not logged because default is prevented."); }} >
<button onClick={(event) => event.preventDefault()} />
</Slot.Root>
);
Previous门户