Slot
Slotは、propsを子要素にマージするコンポーネントです。
const Button = ({ asChild, ...props }) => {
const Component = asChild ? Slot : "button"
return <Component {...props} />
}
return (
<Button
asChild
onClick={(ev) => {
if (!ev.defaultPrevented) {
console.log("Not logged because default is prevented.")
}
}}
>
<a href="/docs/components/slot" onClick={(ev) => ev.preventDefault()}>
Slot
</a>
</Button>
)
使い方
import { Slot, Slottable } from "@yamada-ui/react"
import { Slot, Slottable } from "@/components/ui"
import { Slot, Slottable } from "@workspaces/ui"
<Slot>
<Slottable />
</Slot>
複数の子要素
Slotは単一の子要素のみを受け入れます。複数の子要素を受け入れる場合は、Slottableを使用します。
const Button = ({ asChild, children, endIcon, startIcon, ...props }) => {
const Component = asChild ? Slot : "button"
return (
<Component {...props}>
{startIcon}
<Slottable>{children}</Slottable>
{endIcon}
</Component>
)
}
return (
<Button asChild>
<a href="/docs/components/slot">Slot</a>
</Button>
)