# 表单

> 在表单中把 ColorInput 当作 React 颜色输入框使用：设置 name 即可提交，支持 form.reset() 重置，也能参与原生校验。

Source: https://chroma-panel.jscrate.dev/zh/react/handbook/forms
Last updated: 2026-09-21

给 `ColorInput` 设置 `name`，它就成了表单的一部分：提交时带上一个颜色字符串，支持必填校验，表单重置时回到 `defaultValue`。

```tsx
"use client";

import { ColorInput } from "chroma-panel";
import { useState } from "react";

export default function ColorInputFormDemo() {
  const [submitted, setSubmitted] = useState<string | null>(null);

  return (
    <form
      className="flex items-center gap-3"
      onSubmit={(event) => {
        event.preventDefault();
        const data = new FormData(event.currentTarget);
        setSubmitted(String(data.get("brand")));
      }}
    >
      <ColorInput name="brand" defaultValue="#cc3366" injectStyles={false} />

      <button
        type="submit"
        className="rounded-md border border-edge px-3 py-1.5 text-sm font-medium"
      >
        Submit
      </button>

      <button
        type="reset"
        className="rounded-md px-3 py-1.5 text-sm font-medium text-muted-foreground"
        onClick={() => setSubmitted(null)}
      >
        Reset
      </button>

      {submitted && (
        <span className="font-mono text-sm text-muted-foreground">
          {submitted}
        </span>
      )}
    </form>
  );
}
```

```tsx
<form onSubmit={handleSubmit}>
  <ColorInput name="brand" defaultValue="#cc3366" required />
  <button type="submit">Save</button>
</form>
```

提交的值是按你设置的 `format` 生成的字符串，所以需要 `rgba()` 的表单可以直接拿到，不用你再转换一次。所有格式见[序列化](https://chroma-panel.jscrate.dev/zh/react/utils/serializing)。

要给它加标签，就给它设置 `id`，再让你自己的 `<label htmlFor>` 指向它。如果没有可见的标签，就传入 `aria-label`。更多内容见[无障碍功能](https://chroma-panel.jscrate.dev/zh/react/overview/accessibility)。

## 校验

设置 `required` 后，控件为空时会被标记为无效。`validationBehavior` 决定是使用浏览器自带的气泡提示，还是只通过 ARIA 提供提示信息：

```tsx
<ColorInput name="brand" required validationBehavior="aria" />
```

## 重置

和原生输入框一样，`form.reset()` 会把控件恢复为 `defaultValue`。受控的 `ColorInput` 则需要你自己重置，因为表单改不了由你掌管的状态。详见[受控与非受控](https://chroma-panel.jscrate.dev/zh/react/handbook/controlled)。

## API 参考

### Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `open` | `boolean` | — | Whether the popover is open, when you control it. |
| `defaultOpen` | `boolean` | `false` | Whether the popover starts open. |
| `onOpenChange` | `(open: boolean) => void` | — | Fires when the popover opens or closes, however it was triggered. |
| `name` | `string` | — | Submits with the surrounding form under this name. The submitted value is the string in whichever `format` you set. |
| `form` | `string` | — | Associates the control with a form by id, for when it cannot be nested inside one. |
| `required` | `boolean` | `false` | Marks the control invalid while it has no value. |
| `readOnly` | `boolean` | `false` | Shows the color but does not allow changing it. Unlike `disabled`, the value still submits. |
| `autoComplete` | `string` | — | Passed through to the hidden input backing the control. |
| `validationBehavior` | `"native" \| "aria"` | `'native'` | `'native'` uses the browser's own validation bubble. `'aria'` reports the message through ARIA only, for when you render your own. |
| `id` | `string` | — | Id on the trigger, so your own `<label htmlFor>` can point at it. |
| `aria-label` | `string` | `'Choose a color'` | Accessible name for the trigger, used when there is no visible label. |
| `triggerClassName` | `string` | — | Class on the swatch button only. Equivalent to `classNames.trigger`. |
| `value` | `string \| Hsva` | — | The color, when you keep it in your own state. Inherited from ChromaPanel. |
| `defaultValue` | `string \| Hsva` | `'#3366cc'` | The starting color, when you want the panel to keep it. Inherited from ChromaPanel. |
| `onChange` | `(color: ColorChangeResult) => void` | — | Fires continuously while a drag is in progress. Inherited from ChromaPanel. |
| `onChangeComplete` | `(color: ColorChangeResult) => void` | — | Fires once when the drag ends. Use it for saving, undo entries and network calls. Inherited from ChromaPanel. |
| `onValueChange` | `(color: ColorChangeResult, meta: ColorChangeMeta) => void` | — | Fires continuously with interaction metadata, including the change source. Inherited from ChromaPanel. |
| `onValueCommit` | `(color: ColorChangeResult, meta: ColorChangeMeta) => void` | — | Fires once per completed interaction with phase and source metadata. Inherited from ChromaPanel. |
| `modes` | `readonly (ModeId \| string \| PickerMode)[]` | `all five` | Which tabs appear, in the order you list them. Inherited from ChromaPanel. |
| `mode` | `string` | — | The open tab, when you control it. Inherited from ChromaPanel. |
| `defaultMode` | `string` | `first mode` | The tab to open on. Inherited from ChromaPanel. |
| `onModeChange` | `(mode: string) => void` | — | Fires when the reader switches tabs. Inherited from ChromaPanel. |
| `format` | `ColorFormat` | `'hex'` | Sets the `css` string on the change result, and the value a form submits. Inherited from ChromaPanel. |
| `showAlpha` | `boolean` | `true` | Turn off when opacity is not allowed. Inherited from ChromaPanel. |
| `showEyedropper` | `boolean` | `true` | Turn off to hide the eyedropper even where it is supported. Inherited from ChromaPanel. |
| `showCopyButton` | `boolean` | `true` | Show a button that copies the color in the configured format. Inherited from ChromaPanel. |
| `showRecentColors` | `boolean` | `true` | Turn off in a one-shot picker. Inherited from ChromaPanel. |
| `recentColors` | `string[]` | — | The recent-color history, when you keep it. Persist it yourself to carry the list between sessions. Inherited from ChromaPanel. |
| `defaultRecentColors` | `string[]` | `[]` | The starting history, when you want the panel to keep it. Inherited from ChromaPanel. |
| `onRecentColorsChange` | `(colors: string[]) => void` | — | Fires with the whole list whenever a color is added to it. Inherited from ChromaPanel. |
| `palettes` | `ColorPalette[]` | `built-in set` | Replaces the palette swatches with your own. Inherited from ChromaPanel. |
| `pencils` | `string[]` | `built-in 120-color grid` | Replaces the pencil grid. Inherited from ChromaPanel. |
| `modeProps` | `Record<string, Record<string, unknown>>` | — | Props spread onto one mode's panel, keyed by mode id. Lets a custom mode take props without the panel knowing about it. Inherited from ChromaPanel. |
| `imageOptions` | `ExtractOptions` | — | Shorthand for `modeProps.image.extractOptions`. Inherited from ChromaPanel. |
| `disabled` | `boolean` | `false` | Makes the panel read-only. Inherited from ChromaPanel. |
| `theme` | `"dark" \| "light"` | `system` | Forces one theme instead of following the OS. Inherited from ChromaPanel. |
| `showTitleBar` | `boolean` | `true` | Turn off for an inline panel with no chrome. Inherited from ChromaPanel. |
| `title` | `string` | `'Colors'` | The title bar text. Inherited from ChromaPanel. |
| `onClose` | `() => void` | — | Fires when the red window control is used. An inline panel has nothing to close, so that control is dimmed until you pass this. Inherited from ChromaPanel. |
| `collapsed` | `boolean` | — | Whether the panel is collapsed to its title bar, when you control it. Inherited from ChromaPanel. |
| `defaultCollapsed` | `boolean` | `false` | Whether it starts collapsed. Collapsing hides the body with CSS rather than unmounting, so nothing is lost. Inherited from ChromaPanel. |
| `onCollapsedChange` | `(collapsed: boolean) => void` | — | Fires when the yellow window control is used. Inherited from ChromaPanel. |
| `size` | `PanelSize` | — | The panel size, when you control it. Inherited from ChromaPanel. |
| `defaultSize` | `PanelSize` | `'default'` | The starting size. `'expanded'` widens the panel, and the wheel with it. Inherited from ChromaPanel. |
| `onSizeChange` | `(size: PanelSize) => void` | — | Fires when the green window control is used. Inherited from ChromaPanel. |
| `injectStyles` | `boolean` | `true` | Turn off when you import `chroma-panel/style.css` yourself, as this site does. Inherited from ChromaPanel. |
| `className` | `string` | — | Class applied to the panel root. Inherited from ChromaPanel. |
| `classNames` | `ChromaClassNames` | — | Classes applied per part. Inherited from ChromaPanel. |
| `style` | `React.CSSProperties` | — | Inline styles on the panel root. Setting the `--cp-*` custom properties here themes a single panel. Inherited from ChromaPanel. |
| `store` | `ColorStore` | — | An external color store, for driving several panels from one color. Inherited from ChromaPanel. |
