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

FieldControlState

Defined in: hooks/types.ts:40

Состояние поля формы, возвращаемое хуком useFormControl для FieldNode.

Содержит реактивные данные поля: значение, состояние валидации, флаги взаимодействия и пользовательские props для компонентов.

Example

interface Props {
control: FieldNode<string>;
}

function TextField({ control }: Props) {
const state = useFormControl(control);

return (
<div>
<input
value={state.value}
disabled={state.disabled}
onChange={e => control.setValue(e.target.value)}
/>
{state.shouldShowError && state.errors[0] && (
<span className="error">{state.errors[0].message}</span>
)}
</div>
);
}

See

Type Parameters

T

T

Тип значения поля (string, number, boolean и т.д.)

Properties

componentProps

componentProps: Record<string, any>;

Defined in: hooks/types.ts:203

Пользовательские props для передачи в UI-компоненты. Устанавливаются через FieldNode.setComponentProps.

Example

// Установка props
field.setComponentProps({
placeholder: 'Enter email...',
maxLength: 100,
autoComplete: 'email'
});

// Использование в компоненте
const { componentProps, value } = useFormControl(field);

return (
<input
value={value}
placeholder={componentProps.placeholder}
maxLength={componentProps.maxLength}
autoComplete={componentProps.autoComplete}
/>
);

disabled

disabled: boolean;

Defined in: hooks/types.ts:87

Флаг отключения поля. true когда поле недоступно для редактирования.

Example

const { disabled, value } = useFormControl(field);

return (
<input
value={value}
disabled={disabled}
className={disabled ? 'opacity-50' : ''}
/>
);

errors

errors: ValidationError[];

Defined in: hooks/types.ts:106

Массив ошибок валидации. Пустой массив означает отсутствие ошибок.

Example

const { errors } = useFormControl(field);

return (
<ul className="error-list">
{errors.map((error, i) => (
<li key={i}>{error.message}</li>
))}
</ul>
);

invalid

invalid: boolean;

Defined in: hooks/types.ts:140

Флаг невалидности поля. true когда есть ошибки валидации (errors.length > 0). Противоположность valid.

Example

const { invalid } = useFormControl(field);

return (
<input
aria-invalid={invalid}
className={invalid ? 'border-red' : ''}
/>
);

pending

pending: boolean;

Defined in: hooks/types.ts:68

Флаг асинхронной валидации или загрузки. true когда выполняется асинхронный валидатор.

Example

const { pending } = useFormControl(usernameField);

return (
<div>
<input {...props} />
{pending && <Spinner size="small" />}
</div>
);

shouldShowError

shouldShowError: boolean;

Defined in: hooks/types.ts:174

Флаг для отображения ошибки. Комбинация touched && invalid - удобный shortcut для UI.

Example

const { shouldShowError, errors } = useFormControl(field);

return (
<div>
<input {...props} />
{shouldShowError && (
<span className="error">{errors[0]?.message}</span>
)}
</div>
);

touched

touched: boolean;

Defined in: hooks/types.ts:154

Флаг взаимодействия с полем. true после того как поле потеряло фокус (blur) хотя бы один раз.

Example

const { touched, invalid } = useFormControl(field);

// Показываем ошибку только после взаимодействия
const showError = touched && invalid;

valid

valid: boolean;

Defined in: hooks/types.ts:121

Флаг валидности поля. true когда поле прошло все валидации (errors.length === 0).

Example

const { valid } = useFormControl(field);

return (
<input className={valid ? 'border-green' : 'border-gray'} />
);

value

value: T;

Defined in: hooks/types.ts:50

Текущее значение поля.

Example

const { value } = useFormControl(emailField);
console.log(value); // "user@example.com"