# Field

把表单控件连接到它的标签、描述和校验错误。

字段把表单控件连接到它的标签、描述和它显示的错误，并为你接好 `id`、`for` 和 `aria-describedby`。

```tsx title="input.tsx"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"

function Example() {
  return (
    <div data-slot="stack">
      <Field>
        <FieldLabel>Username</FieldLabel>
        <Input name="username" placeholder="hollis" autoComplete="username" />
        <FieldDescription>
          Choose a unique username for your account.
        </FieldDescription>
      </Field>
    </div>
  )
}

export { Example }
```

点击 Username 让输入框获得焦点，然后输入一个名字。

## 安装
```bash
npm install @ui-sdk/react @ui-sdk/core
```

## 组合
用下面的组合构建一个 `Field`：

```text
Field
├── FieldLabel
├── Input
├── FieldDescription
└── FieldError
```

## 用法
```tsx
import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"

function UsernameField() {
  return (
    <Field name="username">
      <FieldLabel>Username</FieldLabel>
      <Input autoComplete="username" required />
      <FieldDescription>This is your public name.</FieldDescription>
      <FieldError />
    </Field>
  )
}

export { UsernameField }
```

控件可以是我们提供的组件，比如 [Input](/docs/react/components/input)、[Textarea](/docs/react/components/textarea)、[Select](/docs/react/components/select) 或 [Checkbox](/docs/react/components/checkbox)，它会自己连接到字段。

标签为控件提供名称，描述和任何显示出来的错误则说明它。

把相关的字段归入一个[字段集](https://ui-sdk.cn/docs/react/components/field#field-sets)：

```tsx
<FieldSet>
  <FieldLegend />
  <FieldDescription />
  <FieldGroup>
    <Field />
    <Field />
  </FieldGroup>
</FieldSet>
```

## 控件
一行文本用 [Input](/docs/react/components/input)，更多内容用 [Textarea](/docs/react/components/textarea)：

```tsx
<Field>
  <FieldLabel>Feedback</FieldLabel>
  <Textarea name="feedback" />
</Field>
```

对于我们不提供的控件，比如原生 `<select>`，请用 `FieldControl`。它渲染一个 `<input>`，或通过 `render` 渲染另一个元素，并用同样的方式把它连接到字段。[智能体](/docs/agents)只能看到我们的组件，所以它无法填写 `FieldControl`：有我们的组件时就用我们的。

```tsx
<Field>
  <FieldLabel>Department</FieldLabel>
  <FieldControl render={<select />} name="department">
    <option value="design">Design</option>
    <option value="engineering">Engineering</option>
  </FieldControl>
</Field>
```

字段里的 [Checkbox](/docs/react/components/checkbox)、[Switch](/docs/react/components/switch) 或 [Radio Group](/docs/react/components/radio) 会使用字段的标签和描述。按压标签会切换复选框或开关。单选组会把字段的标签当作自己的名称，每个单选项则保留自己的标签：

```tsx
<Field>
  <Switch name="mfa" />
  <FieldLabel>Two-factor authentication</FieldLabel>
  <FieldDescription>Ask for a code when you sign in.</FieldDescription>
</Field>

<Field>
  <FieldLabel>Plan</FieldLabel>
  <RadioGroup name="plan" defaultValue="monthly">
    <label>
      <Radio value="monthly" />
      Monthly
    </label>
    <label>
      <Radio value="yearly" />
      Yearly
    </label>
  </RadioGroup>
</Field>
```

## 校验
使用原生约束，比如 `required`、`type="email"` 和 `pattern`。错误会在尝试提交后出现，并随值的变化而更新。第一个无效的控件会获得焦点。

把错误留空可显示浏览器的消息；要用自己的消息，就用 `match="valueMissing"` 和 `match="typeMismatch"`。加上错误部件后，页面里的这条消息会取代浏览器原生的校验气泡。

```tsx title="validation.tsx"
import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <form
      data-slot="stack"
      onSubmit={(event) => {
        event.preventDefault()
        log(`Subscribed ${new FormData(event.currentTarget).get("email")}`)
      }}
    >
      <Field name="email">
        <FieldLabel>Email</FieldLabel>
        <Input type="email" required placeholder="hollis@example.com" />
        <FieldDescription
          render={(props, state) => (
            <p {...props}>
              {state.valid
                ? "Looks good."
                : "We'll send you a confirmation link."}
            </p>
          )}
        />
        <FieldError match="valueMissing">Enter your email address.</FieldError>
        <FieldError match="typeMismatch">
          Enter an email address like hollis@example.com.
        </FieldError>
      </Field>
      <Field name="website">
        <FieldLabel>Website</FieldLabel>
        <Input type="url" required placeholder="https://example.com" />
        <FieldError />
      </Field>
      <button type="submit" data-variant="solid">
        Subscribe
      </button>
    </form>
  )
}

export { Example }
```

在邮箱为空或无效时点击 Subscribe，然后改正它来清除错误。

## 来自你的代码的错误
当服务器或表单库给出错误时，传入 `invalid`。`true` 会立即显示它。清除值即可回到浏览器的校验。

给这个错误单独的文本，并把 `match` 设为 `true`。`valueMissing` 这类具名匹配仍然指原生校验。`invalid={false}` 会隐藏字段的无效状态，但不会让无效的原生控件通过校验。

```tsx
<Field name="email" invalid={serverError ? true : undefined}>
  <FieldLabel>Email</FieldLabel>
  <Input type="email" required onValueChange={() => setServerError(null)} />
  <FieldError match="valueMissing">Enter your email address.</FieldError>
  {serverError && <FieldError match>{serverError}</FieldError>}
</Field>
```

## 必填与禁用
必填控件会给每个部件标记 `data-required`，部件的状态里也有 `required`，所以只靠 CSS 就能让标签显示标记。

禁用的字段会禁用它的控件，并给每个部件标记 `data-disabled`，就像[禁用的字段集](https://ui-sdk.cn/docs/react/components/field#disabled-field-sets)对它里面的每个字段所做的那样。

## 字符计数
把文本放在状态里，并在描述里显示它的长度。在控件上设置 `maxLength`，让这个限制生效。

```tsx
<Field>
  <FieldLabel>Bio</FieldLabel>
  <Textarea
    maxLength={280}
    value={bio}
    onValueChange={(value) => setBio(value)}
  />
  <FieldDescription>{bio.length} / 280</FieldDescription>
</Field>
```

## 表单
控件用自己的 `name` 提交它的值；没有 `name` 时，就用字段的 `name`。重置会恢复控件的默认值，并隐藏校验错误。禁用的控件不会包含在提交的值里。共享的表单行为见[表单](/docs/react/forms)。

## 字段集
字段集把相关的字段归到一个图例（legend）下，并一起禁用它们。

```tsx title="field-set.tsx"
import {
  Field,
  FieldDescription,
  FieldGroup,
  FieldLabel,
  FieldLegend,
  FieldSet,
} from "@ui-sdk/react/field"
import { Input } from "@ui-sdk/react/input"

function Example() {
  return (
    <FieldSet>
      <FieldLegend>Address</FieldLegend>
      <FieldDescription>
        We need your address to deliver your order.
      </FieldDescription>
      <FieldGroup>
        <Field name="street">
          <FieldLabel>Street address</FieldLabel>
          <Input autoComplete="street-address" />
        </Field>
        <div data-slot="grid">
          <Field name="city">
            <FieldLabel>City</FieldLabel>
            <Input autoComplete="address-level2" />
          </Field>
          <Field name="postal-code">
            <FieldLabel>Postal code</FieldLabel>
            <Input autoComplete="postal-code" />
          </Field>
        </div>
      </FieldGroup>
    </FieldSet>
  )
}

export { Example }
```

在地址字段之间移动。它们的图例和描述为这个分组命名。

`FieldSet` 是原生 `<fieldset>`，`FieldLegend` 是原生 `<legend>`，所以字段集在脚本运行之前就有了名称，也能被禁用。让图例保持为第一个子元素。用其他元素渲染的图例，比如 `render={<div />}`，仍然通过 `aria-labelledby` 为字段集命名。

直接放在字段集里、不在任何 `Field` 之内的 `FieldDescription` 描述的是字段集，所以焦点进入时屏幕阅读器会读出它。`FieldGroup` 是一个堆叠字段的 `<div>`，没有角色也没有状态：为分组命名和禁用的都是字段集。

## 禁用字段集
禁用字段集会禁用它的控件和嵌套的字段集。表单提交时不会包含它们的值。

```tsx
<FieldSet disabled={sameAsShipping}>
  <FieldLegend>Billing address</FieldLegend>
  <Field name="billing-street">
    <FieldLabel>Street address</FieldLabel>
    <Input autoComplete="billing street-address" />
  </Field>
</FieldSet>
```

## 字段集里的分组
图例会为字段集里的[复选框组](https://ui-sdk.cn/docs/react/components/checkbox#group)或[单选组](/docs/react/components/radio)命名，所以分组不需要自己的标签。

```tsx
<FieldSet>
  <FieldLegend>Notifications</FieldLegend>
  <CheckboxGroup name="notify" defaultValue={["mentions"]}>
    <label>
      <Checkbox value="mentions" />
      Mentions
    </label>
    <label>
      <Checkbox value="follows" />
      New followers
    </label>
  </CheckboxGroup>
</FieldSet>
```

## 自定义渲染
每个部件都接受 `render`，用来在原地渲染别的元素或组件，比如 `FieldControl` 上的 `render={<select />}`。作为函数时，它会收到要展开的 props 和字段的状态：

```tsx
<FieldDescription
  render={(props, state) => (
    <p {...props}>
      {state.invalid ? "Use letters and numbers only." : "Letters and numbers."}
    </p>
  )}
/>
```

`className` 和 `style` 也可以是状态的函数。`FieldError` 的状态里还有当前问题的 `message`。

状态是惰性读取的。只有当部件的渲染函数或槽位读过某个值时，这个值的变化才会让部件重新渲染。每个部件的状态列在[状态](https://ui-sdk.cn/docs/react/components/field#state)下。

## 自定义控件
`useFieldControl` 让你自己的控件像我们的控件一样加入它周围的字段。在字段之外，它返回 `null`。在字段之内，它返回：

- `name`：字段的 `name`，供没有自己设置 `name` 的控件使用。
- `disabled`：字段是否被禁用。
- `props(props)`：把字段的 props 合并进控件的 props：`id`、`aria-labelledby`、`aria-describedby`、`aria-invalid`、`disabled` 和字段的数据属性，以及一个告诉字段哪个元素是它控件的 ref。控件保留自己的 `data-slot`。

字段变化时控件会重新渲染，比如它的标签或错误出现时。

```tsx
import * as React from "react"
import { useFieldControl } from "@ui-sdk/react/field"

export function PhoneInput(props: React.ComponentProps<"input">) {
  const field = useFieldControl()
  const input = {
    type: "tel",
    autoComplete: "tel",
    name: field?.name,
    ...props,
    "data-slot": "phone-input",
  }
  return <input {...(field ? field.props(input) : input)} />
}
```

```tsx
<Field>
  <FieldLabel>Phone</FieldLabel>
  <PhoneInput required />
  <FieldError />
</Field>
```

字段会从它里面的原生 input、select 和 textarea 读取有效性，所以上面的 input 上 `required` 和 `pattern` 能生效。不是原生 input 的控件，比如一排按钮，会通过自己的一个原生 input 参与：我们的控件会在它旁边渲染一个视觉上隐藏的 input。

想用我们的控件所用的原语（primitive）从零构建控件，请参阅[原语](/docs/core/kernel/define-a-primitive)。

## 样式
校验用 `data-invalid` 和 `data-valid`，其余用 `data-focused`、`data-required` 和 `data-disabled`。字段的每个部件都会拿到相同的属性，所以标签可以随控件一起变红。

每个部件都有一个 `data-slot`，比如 `field-label`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/react/components/field#data-attributes)下。

## 数据属性
### Field
`[data-slot="field"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### FieldLabel
`[data-slot="field-label"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### FieldControl
`[data-slot="field-control"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### FieldDescription
`[data-slot="field-description"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### FieldError
`[data-slot="field-error"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### FieldSet
`FieldGroup` 有 `data-slot="field-group"`，没有状态属性。

`[data-slot="field-set"]`

- `data-disabled`: Present when the field set is disabled, by its own prop or a `<fieldset>` around it.

### FieldLegend
`[data-slot="field-legend"]`

- `data-disabled`: Present when the field set is disabled, by its own prop or a `<fieldset>` around it.

### FieldSet 里的 FieldDescription
`[data-slot="field-description"]`

- `data-disabled`: Present when the field set is disabled, by its own prop or a `<fieldset>` around it.

## API 参考
属性与下面相同，都作为 React props 传入。

字段没有变更事件。从部件的数据属性或渲染函数里读取它的状态。设置 `debug` 可以记录每次状态变化及其原因。

### Field
- `name?` (`string`): The name the control submits under, when the control doesn't set its own.
- `disabled?` (`boolean`): Disables the control, and marks every part.
- `invalid?` (`boolean`): Whether the field shows as invalid, when your code decides, like a form library or an error from the server. `true` shows its errors now, `false` shows none whatever the browser thinks. Leave it out to show the browser's own validation once a submit finds the field invalid.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### FieldError
- `match?` (`boolean | ValidityKey`): When this error shows. `true` shows it always and `false` never. A validity flag, like `"valueMissing"`, shows it only for that problem of the browser's own validation. Without it, any problem shows it.

### FieldSet
- `disabled?` (`boolean`): Disables every control inside it, except those in its legend, and leaves them out of the form.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### 状态
- `disabled` (`boolean`): Whether the field is disabled, by itself or by a `<fieldset>`.
- `required` (`boolean`): Whether the control is required, read from its `required` or `aria-required`.
- `focused` (`boolean`): Whether focus is inside the control.
- `invalid` (`boolean`): Whether the field shows as invalid: `invalid` when you pass it, else the browser's validation once shown.
- `valid` (`boolean`): Whether the browser's validation passes, once shown. Always false while you pass `invalid`.

- `disabled` (`boolean`): Whether the field is disabled, by itself or by a `<fieldset>`.
- `required` (`boolean`): Whether the control is required, read from its `required` or `aria-required`.
- `focused` (`boolean`): Whether focus is inside the control.
- `invalid` (`boolean`): Whether the field shows as invalid: `invalid` when you pass it, else the browser's validation once shown.
- `valid` (`boolean`): Whether the browser's validation passes, once shown. Always false while you pass `invalid`.
- `message` (`string`): The browser's message for the current problem. Children you pass show instead.

`FieldDescription` 会收到字段的状态；当它描述字段集时，只收到 `disabled`。

- `disabled` (`boolean`): Whether the field set is disabled, by itself or by a field set around it. Whether the field is disabled, by itself or by a `<fieldset>`.
- `required` (`boolean | undefined`): Whether the control is required, read from its `required` or `aria-required`.
- `focused` (`boolean | undefined`): Whether focus is inside the control.
- `invalid` (`boolean | undefined`): Whether the field shows as invalid: `invalid` when you pass it, else the browser's validation once shown.
- `valid` (`boolean | undefined`): Whether the browser's validation passes, once shown. Always false while you pass `invalid`.

字段集的每个部件都会收到相同的状态。

- `disabled` (`boolean`): Whether the field set is disabled, by itself or by a field set around it.

## 无障碍
标签通过 `aria-labelledby` 为控件提供名称，控件能接受原生 `<label for>` 时还会同时用它。描述和任何显示出来的错误通过 `aria-describedby` 描述它，无效的控件带有 `aria-invalid`。下面的测试覆盖这些关联和键盘行为。

**Labelling**

- The label names the control.
- The description describes the control.
- Clicking the label of a text field focuses it.

**A label wrapping a field**

- Names the control inside it.
- Checks its control when clicked anywhere.
- Keeps the field's description on its control.
- Names a control that renders after it.
- Keeps the part's data-slot.
- Warns in development only when a label outside a field labels nothing.
- A description and an error outside a field keep their data-slot. Web components only.
- A hidden error outside a field stays hidden whatever display its class gives. Web components only.
- An error outside a field follows its match. Web components only.
- An error outside a field shows a child that arrives after it. Web components only.

**Errors**

- Stay hidden until the form tries to submit.
- Show the browser's message when they have no text of their own.
- Count another library's form-associated element inside the field.
- Describe the control while they show.
- Update as the value changes once shown.
- Update as state set from script changes the value once shown. Web components only.
- A field marked invalid shows its error right away.
- A field marked valid never shows the browser's errors.
- A form reset hides them again.
- Errors in the page replace the browser's message, and the first invalid control takes focus.

Runs in React、Vue 和 web components.

在字段集里：

- The legend names the group.
- A disabled field set disables the controls inside and leaves them out of the form.
- Enabling it again restores the controls.
- A field set disabled from the start disables its required fields.
- Fields in a disabled field set mark their parts disabled.

**Enhancements**

- The description describes the group.

Runs in React、Vue 和 web components.

在表单里：

- The form submits every checked control's name and value.
- Unchecked controls submit nothing.
- A checkbox outside the form joins it with the form attribute.
- Required controls block submission.
- A form reset returns every control to its default.
- A reset returns to the default value, not to nothing.
- A disabled fieldset disables the controls inside it.
- A read-only control still submits.
- A user's change fires native input and change events on the form.

Runs in React、Vue 和 web components.
