# 部件与组合

组合一个组件的部件，并选择它们绑定到哪些元素。

一个组件是一组自定义元素。Popover 有一个根部件用来持有状态，一个触发部件用来打开它，还有一个内容部件用来显示内容。

## 把部件组合起来
导入组件，然后按它的“组合”一节所示嵌套各个部件：

```ts
import "@ui-sdk/web/popover"
```

```html
<ui-popover id="details">
  <ui-popover-trigger><button>Details</button></ui-popover-trigger>
  <ui-popover-content>
    <ui-popover-title>Project Details</ui-popover-title>
    <p>Last updated today.</p>
    <ui-popover-close><button>Done</button></ui-popover-close>
  </ui-popover-content>
</ui-popover>
```

触发部件和关闭部件会包裹你自己的 `<button>`。这些包裹元素使用 `display: contents`，所以按钮直接参与布局。

部件通过查找 DOM 找到它们的根。你可以在部件之间放自己的布局元素。外部部件可以用 `for="id"` 指定自己的根；[控制器](/docs/web-components/controllers) 展示了一个例子。

## 选择元素
当部件应该绑定到它的第一个子元素时，使用 `as-child`。例如，把一个菜单项渲染成链接：

```ts
import "@ui-sdk/web/menu"
```

```html
<ui-menu>
  <ui-menu-trigger><button>Account</button></ui-menu-trigger>
  <ui-menu-content>
    <ui-menu-item as-child><a href="/settings">Settings</a></ui-menu-item>
  </ui-menu-content>
</ui-menu>
```

链接会接收部件的角色、属性和键盘行为。触发部件和关闭部件已经使用它们的第一个按钮或链接，所以不需要 `as-child`。

## 为控件命名
使用标签部件或标题部件，例如 `<ui-field-label>` 或 `<ui-dialog-title>`。对于图标按钮，把 `aria-label` 放在包裹元素内部的原生按钮上。

部件会写入它们管理的属性，包括角色、ID 和 ARIA 状态。其他属性和你自己的监听器会保留。你写在元素上的名称或输入提示也会保留：`aria-label`、`aria-labelledby`、`aria-description`、`title`、`autocomplete`、`autocapitalize`、`autocorrect`、`inputmode` 和 `spellcheck`。修改标记时，保持这些被管理的属性不变。

## 响应状态
用数据属性做样式，用 DOM 事件处理内容变更。[状态与事件](/docs/web-components/state-and-events) 展示如何监听并取消一次变更。
