# 自定义部件

编写带有自己 React 逻辑的部件，并让它连接到原语。

[渲染原语](/docs/react/rendering) 里的部件足够用，直到其中一个需要自己的逻辑。你可以只替换那个部件，并保留[组合行为](https://ui-sdk.cn/docs/core/compose-behaviors#complete-primitive)里的同一个 `rating.ts` 定义。

## 编写根部件
下面是生成的 `RatingRoot` 的替代实现。`usePrimitive` 创建它的实例，`usePart` 连接 `root` 槽位：

```tsx title="rating-root.tsx"
"use client"

import type { StateOf } from "@ui-sdk/core"
import { usePart, usePrimitive, type PartProps } from "@ui-sdk/react/primitive"
import { rating, type RatingOptions } from "./rating"

function RatingRoot({
  value,
  defaultValue,
  onValueChange,
  ...props
}: RatingOptions &
  Omit<PartProps<"div", StateOf<typeof rating, "root">>, "defaultValue">) {
  const handle = usePrimitive(rating, { value, defaultValue, onValueChange })
  return usePart(handle, "root", {}, props, "div")
}

export { RatingRoot }
```

把原语选项传给 `usePrimitive`，把元素 props 传给 `usePart`。空的 `{}` 用来传槽位 props；这个根不需要任何槽位 props。`usePart` 与子部件共享实例，槽位不存在时不渲染任何内容。

适配器让选项保持最新，并管理实例的生命周期。在事件处理函数或 effect 里调用 `handle.api`。要渲染会变化的状态，就使用部件的 `children` 或 `render` 函数；只读取 `handle.state` 不会订阅变更。

## 连接子部件
子部件可以把原语本身传给 `usePart`。它会找到上方根共享的实例。

这个 `RatingStar` 既能用在上面手写的根里，也能用在生成的 `RatingRoot` 里。它添加了一个默认的无障碍名称：

```tsx
"use client"

import { usePart, type PartProps } from "@ui-sdk/react/primitive"
import { rating } from "./rating"

function RatingStar({
  value,
  ...props
}: { value: string } & Omit<PartProps<"button">, "value">) {
  const label = `${value} ${value === "1" ? "star" : "stars"}`
  return usePart(
    rating,
    "star",
    { value },
    { "aria-label": label, ...props },
    "button"
  )
}

export { RatingStar }
```

`{ value }` 标识这颗星。其余的 props 传给它的按钮。调用方可以用 `aria-label` 覆盖这个名称。

在[渲染评分](https://ui-sdk.cn/docs/react/rendering#render-the-rating)里用它替换生成的星。把它放在 `RatingRoot` 里，这样它才能找到实例。

## 合并 props
当你的部件添加的 props 需要与调用方的 props 合并时，就用 `mergeProps`。例如，输入框可以在获得焦点时选中文本，同时仍然接受 `onFocus` 处理函数：

```tsx
"use client"

import {
  mergeProps,
  renderElement,
  type PartProps,
} from "@ui-sdk/react/primitive"
import type { FocusEvent } from "react"

function SelectOnFocusInput({ render, ...props }: PartProps<"input">) {
  const own = {
    onFocus: (event: FocusEvent<HTMLInputElement>) =>
      event.currentTarget.select(),
  }
  return renderElement("input", mergeProps(own, props), render)
}

export { SelectOnFocusInput }
```

调用方的处理函数先运行，它可以调用 `preventDefault()` 跳过你的处理函数。类名会拼接，样式会合并，ref 会组合。后面参数中的其他值优先；`undefined` 不会替换已有的值。

对于原生的 `pointerenter` 和 `pointerleave` 槽位监听器，取消 React 的处理函数并不会取消槽位的监听器。

## 没有原语的元素
`renderElement` 也适用于普通的包装元素。它给包装元素和其他部件一样的 `render` prop：

```tsx
"use client"

import { renderElement, type PartProps } from "@ui-sdk/react/primitive"

function Card({ render, ...props }: PartProps<"div">) {
  return renderElement("div", props, render)
}

export { Card }
```

`PartProps` 提供元素 props 和 `render`。当 `className`、`style` 或 `children` 需要接收部件的状态时，加上它的第二个类型参数。

`renderElement` 不使用 Hook，所以像 `Card` 这样的包装元素在 Server Component 里也能用。凡是用 `usePrimitive`、`usePart` 或 `createParts` 构建的内容仍然需要客户端组件，因为它们用到了 Hook。[服务端渲染](https://ui-sdk.cn/docs/react/server-rendering#wrappers-in-a-server-component)展示了一个例子。

## 组合浮层
自定义部件可以渲染现有的 Popover 或 Dialog，并连接它的打开状态。[组合现有的浮层](https://ui-sdk.cn/docs/core/behaviors/popups#compose-ours)用一个 emoji 选择器展示了这种连接。
