ユーティリティ

Slot

プロパティを直近の子要素にマージします。

特徴

    独自の `asChild` プロパティをサポートするために使用できます。

インストール

コマンドラインからコンポーネントをインストールします。

npm install @radix-ui/react-slot

構造

コンポーネントをインポートします。

import { Slot } from '@radix-ui/react-slot';
export default () => (
<Slot>
<div>Hello</div>
</Slot>
);

基本例

独自のasChild APIを作成するために使用します。

コンポーネントに単一の子要素がある場合

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

使用コンポーネントに複数の子要素があり、プロパティを正しい要素に渡す場合

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

使用方法

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

イベントハンドラー

on (例: onClick)で始まるプロパティはイベントハンドラーと見なされます。

イベントハンドラーをマージする場合、Slotは、子ハンドラーがスロットハンドラーよりも優先される新しい関数を作成します。

イベントハンドラーの1つがevent.defaultPreventedに依存する場合は、順序が正しいことを確認してください。

import { Slot } from '@radix-ui/react-slot';
export default () => (
<Slot onClick={(event) => { if (!event.defaultPrevented) console.log('Not logged because default is prevented.'); }} >
<button onClick={(event) => event.preventDefault()} />
</Slot>
);