# 第一个组件

添加一个组件到你的页面，并依据它的状态设置样式。

我们来添加一个 **Bookmark** 开关按钮。按压一次打开它，再按压一次关闭。

如果你还没有安装这些包，先看 [安装](/docs/web-components/installation)。

这个例子使用能解析包导入并编译 TypeScript 的打包工具，例如 Vite。把 `index.html` 和 `bookmark-button.ts` 放在同一个文件夹里。

## 注册组件
创建 `bookmark-button.ts`，导入 toggle 入口：

```ts title="bookmark-button.ts"
import "@ui-sdk/web/toggle"
```

导入 toggle 入口会注册 `<ui-toggle>`。这个自定义元素管理被包裹按钮的按压状态，并为屏幕阅读器设置 `aria-pressed`。原生按钮处理 Enter 和 Space。

## 在页面上使用它
把这段标记加到 `index.html`：

```html title="index.html"
<ui-toggle id="bookmark">
  <button type="button">Bookmark</button>
</ui-toggle>

<script type="module" src="./bookmark-button.ts"></script>
```

打开你的页面。你应该会看到一个标着 **Bookmark** 的按钮。接下来添加样式，让你能看出它什么时候处于按压状态。

## 添加样式
开关按钮被按压时，它内部的按钮会带有一个 `data-pressed` 属性。给 `<ui-toggle>` 里的按钮设置样式。

在你的应用里配置好 Tailwind CSS 后，把工具类加到按钮上。开关按钮被按压期间，`data-pressed:` 变体会生效：

```html title="index.html"
<ui-toggle id="bookmark">
  <button
    type="button"
    class="inline-flex h-8 items-center rounded-md border border-neutral-300 px-3 text-sm font-medium hover:bg-neutral-100 focus-visible:outline-2 focus-visible:outline-offset-2 data-pressed:bg-neutral-900 data-pressed:text-white"
  >
    Bookmark
  </button>
</ui-toggle>

<script type="module" src="./bookmark-button.ts"></script>
```

把组件的导入保留在 `bookmark-button.ts` 里：

```ts title="bookmark-button.ts"
import "@ui-sdk/web/toggle"
```

试试设置好样式的开关按钮：

```ts title="first-component.ts"
import "@ui-sdk/web/toggle"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-toggle>
      <button type="button" data-variant="outline">
        Bookmark
      </button>
    </ui-toggle>
  `
}

export { mount }
```

点击 Bookmark 打开或关闭它。实心背景表示它已打开。你也可以用 Tab 聚焦按钮，然后按 Enter 或 Space。

两种状态下都保持标签不变。`aria-pressed` 告诉屏幕阅读器开关是否已打开。

## 继续深入
- [Toggle](/docs/web-components/components/toggle) 介绍禁用状态、受控状态和开关组。
- [组件](/docs/web-components/components) 列出用同一套安装就能添加的其他组件。
- [部件与组合](/docs/web-components/parts-and-composition) 展示如何把一个由多个部件组成的组件拼起来。
- [状态与事件](/docs/web-components/state-and-events) 展示如何读取变更，并从你的应用控制状态。
- [样式与动画](/docs/web-components/styling-and-animation) 涵盖状态属性、CSS 变量和过渡。
