Перейти к основному содержанию

Обзор

Используйте Field, чтобы сгруппировать один элемент управления с его доступной меткой и вспомогательным текстом. Такие компоненты, как Input, напрямую интегрируются с полем.

Использование

Field.Root управляет именем элемента управления, состоянием отключения и валидностью. Field.Label и Field.Description связывают своё содержимое с элементом управления. Настройте время валидации с помощью validationMode; для пользовательской валидации используйте validate.

Анатомия

Поместите один элемент управления и его вспомогательные части внутрь Field.Root. Это дерево показывает поле, созданное с помощью стилизованного компонента Input.
Input и Textarea уже интегрированы с полем. Поместите их непосредственно внутрь Root; они сами обеспечивают поведение элемента управления. Составные элементы управления, такие как Выбор, сохраняют собственный корневой элемент и части внутри поля.

Внешние ошибки

Используйте invalid, когда ваше приложение управляет состоянием ошибки. Явный match делает сообщение об ошибке видимым.
Формулируйте сообщения об ошибках так, чтобы было понятно, что делать, и добавляйте видимую метку, даже если у элемента управления есть заполнитель.

Сгруппированные элементы управления

Используйте Field.Item внутри группы переключателей или флажков, чтобы связать каждый вариант с собственной меткой и описанием. Размещайте метку группы за пределами элементов. Элемент можно отключить независимо; отключённый Field.Root отключает все элементы.

Нативная интеграция и типы

Field сохраняет время выполнения валидации Base UI, пользовательскую валидацию, значения управляемых и неуправляемых элементов управления, а также сведения о событиях изменения значений. Validity предоставляет результат валидации через функцию дочерних элементов. Интегрированные элементы управления сохраняют своё нативное поведение в форме. Root, Item, Label, Control, Description и Error передают нативные props, refs и композицию render. Их элементами по умолчанию являются div, div, label, input, paragraph и div соответственно. Validity не отображает собственный элемент. Импортируйте FieldRootProps, FieldItemProps, FieldLabelProps, FieldControlProps, FieldDescriptionProps, FieldErrorProps и FieldValidityProps из twenty-ui/primitives/input для контрактов соответствующих вышестоящих частей.

Свойства

Справочник генерируется на основе публичных типов компонентов. Нативные атрибуты, включая доступные имена и обработчики событий, также принимаются в частях, рендерящих элементы.

Field.Root

RefObject<FieldRootActions | null>
A ref to imperative actions.
  • validate: Validates the field when called.
string | ((state: FieldRootState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
boolean
Whether the field’s value has been changed from its initial value. Useful when the field state is controlled by an external library.
boolean
по умолчанию:"false"
Whether the component should ignore user interaction. Takes precedence over the disabled prop on the <Field.Control> component.
boolean
Whether the field is invalid. Useful when the field state is controlled by an external library.
string
Identifies the field when a form is submitted. Takes precedence over the name prop on the <Field.Control> component.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, FieldRootState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: FieldRootState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.
boolean
Whether the field has been touched. Useful when the field state is controlled by an external library.
((value: unknown, formValues: Record<string, any>) => string | void | string[] | Promise<string | void | string[] | null> | null)
A function for custom validation. Return a string or an array of strings with the error message(s) if the value is invalid. Returning nothing, null, an empty string, or an empty array means the value is valid. Asynchronous functions are supported, but they do not prevent form submission when using validationMode="onSubmit".
number
по умолчанию:"0"
How long to wait between validate callbacks if validationMode="onChange" is used. Specified in milliseconds.
"onBlur" | "onChange" | "onSubmit"
по умолчанию:"onSubmit"
Determines when the field should be validated. This takes precedence over the validationMode prop on <Form>.
  • onSubmit: triggers validation when the form is submitted, and re-validates on change after submission.
  • onBlur: triggers validation when the control loses focus.
  • onChange: triggers validation on every change to the control value.

Field.Item

string | ((state: FieldItemState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
boolean
по умолчанию:"false"
Whether the wrapped control should ignore user interaction. The disabled prop on <Field.Root> takes precedence over this.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, FieldItemState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: FieldItemState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Field.Label

string | ((state: FieldLabelState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
boolean
по умолчанию:"true"
Whether the component renders a native <label> element when replacing it via the render prop. Set to false if the rendered element is not a label (for example, <div>).This is useful to avoid inheriting label behaviors on <button> controls (such as <Select.Trigger> and <Combobox.Trigger>), including avoiding :hover on the button when hovering the label, and preventing clicks on the label from firing on the button.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, FieldLabelState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: FieldLabelState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Field.Control

string | ((state: FieldControlState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
string | number | readonly string[]
The default value of the input. Use when uncontrolled.
((value: string, eventDetails: { reason: "none"; event: Event; cancel: () => void; allowPropagation: () => void; isCanceled: boolean; isPropagationAllowed: boolean; trigger: Element | undefined; }) => void)
Callback fired when the value changes. Use when controlled.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, FieldControlState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: FieldControlState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Field.Description

string | ((state: FieldDescriptionState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, FieldDescriptionState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: FieldDescriptionState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Field.Error

string | ((state: FieldErrorState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
boolean | keyof ValidityState
Determines whether to show the error message according to the field’s ValidityState. Specifying true will always show the error message, and lets external libraries control the visibility.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, FieldErrorState>
Allows you to replace the component’s HTML element with a different tag, or compose it with another component.Accepts a ReactElement or a function that returns the element to render.
CSSProperties | ((state: FieldErrorState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Field.Validity

(state: FieldValidityState) => ReactNode
обязательно
A function that accepts the field validity state as an argument.