Resumen
NumberField expone las siete partes del campo numérico de Base UI instalado: Root, Group, Input, Decrement, Increment, ScrubArea y ScrubAreaCursor. Impórtalo desde twenty-ui/primitives/input. Conserva el estado numérico, el formato, el incremento, los detalles de eventos y la integración con formularios nativos de Base UI con los estilos de Twenty UI para la entrada, el grupo y los controles de ajuste.
Para el ajuste preestablecido compacto con formato fijo y valores predeterminados de pasos modificadores, usa NumberStepper de twenty-ui/components/input.
”Uso”
Root posee el estado numérico. Input es la entrada de texto visible. Usa Group para organizar controles opcionales de disminución e incremento a su alrededor. Proporciona contenido y nombres accesibles para los controles; el primitivo no inserta iconos ni etiquetas.
Field.Label, Field.Description y Field.Error se asocian con la entrada visible. Como alternativa, pasa aria-label o aria-labelledby a Input. El valor predeterminado de aria-roledescription es Number field; no proporciona un nombre accesible.
Valores y callbacks
Omitevalue para un campo no controlado y proporciona un defaultValue numérico cuando se necesite un valor inicial. Al omitir defaultValue, se inicia vacío. Para un campo controlado, pasa un número o null mediante value y actualízalo desde onValueChange.
null, incluso cuando se establece min. Los borradores incompletos, como -, siguen siendo editables sin informar un número no válido. La escritura analizable actualiza el valor numérico antes de confirmar la edición. El primer paso desde un valor vacío comienza en cero limitado por los límites; los pasos posteriores usan la cantidad de paso activa.
onValueChange(value, details) conserva el event, reason, cancel, allowPropagation, isCanceled, isPropagationAllowed, trigger nativo y el direction opcional. Los motivos distinguen entre escritura (input-change), borrado (input-clear), normalización al perder el foco (input-blur), pegado (input-paste), pulsaciones de teclado, incremento o disminución, rueda, arrastre y autocompletado nativo (none). Llamar a cancel() evita la actualización del estado numérico; los llamadores controlados siguen eligiendo el valor aceptado.
onValueCommitted(value, details) se ejecuta al perder el foco después de editar, al soltar el puntero después de incrementar, disminuir o arrastrar, e inmediatamente para los ajustes con teclado y rueda. Al borrar se confirma null al perder el foco. Los detalles de confirmación contienen event y reason; son detalles genéricos sin métodos para cancelar cambios. Enfocar y desenfocar un campo sin modificar no confirma por sí mismo un valor cuando no se necesita normalización numérica. Las opciones explícitas de redondeo pueden normalizar y confirmar un valor sin modificar.
Configuración regional y formato
Establecelocale y format en Root. Mantienen el contrato instalado de Base UI: locale acepta Intl.LocalesArgument y format acepta Intl.NumberFormatOptions. El formato de visualización es independiente del valor numérico sin procesar enviado por el formulario. El primitivo no fuerza dígitos latinos, agrupación, precisión ni pasos modificadores.
Pasos y límites
step tiene como valor predeterminado 1, smallStep 0.1 mientras se mantiene pulsada Alt y largeStep 10 mientras se mantiene pulsada Shift. El paso activo se aplica a los botones, Flecha arriba y Flecha abajo, la rueda y el movimiento del área de arrastre. snapOnStep tiene como valor predeterminado false; actívalo para ajustar los cambios al paso activo. Inicio y Fin seleccionan el límite explícito correspondiente. Los controladores nativos de teclas pueden llamar a event.preventBaseUIHandler() cuando el propietario necesita anular el comportamiento de teclado de Base UI.
min y max son inclusivos. Las interacciones de paso se mantienen dentro de los límites. De forma predeterminada, los valores escritos y pegados también se limitan numéricamente, y el borrador se normaliza al perder el foco. Establece allowOutOfRange para aceptar ediciones directas fuera de esos límites y permitir que la validación nativa de rango o la validación de la aplicación informe del problema.
step="any" desactiva la validación nativa de pasos mientras que los pasos interactivos usan 1 y los pasos modificadores configurados. Con un paso numérico, proporciona min explícitamente cuando el envío nativo debe validar la alineación de los pasos. El paso numérico no redondea cada valor escrito a un paso.
Arrastre
ScrubArea cambia el valor numérico a medida que se mueve el puntero. Admite movimiento horizontal o vertical, pixelSensitivity y teleportDistance opcional. El paso activo y los límites también se aplican al arrastre. Usa una etiqueta visible como destino de arrastre mientras mantienes la entrada disponible para la edición con teclado.
Compón ScrubAreaCursor dentro de ScrubArea para usar un cursor personalizado durante el arrastre con bloqueo de puntero. Se lleva mediante portal al cuerpo del documento mientras está activo. Base UI recurre al cursor normal para la entrada táctil, el bloqueo de puntero denegado y WebKit. Establece allowWheelScrub en Root para permitir el ajuste con la rueda mientras la entrada está enfocada y bajo el cursor; su valor predeterminado es false.
Formularios y estado deshabilitado
Root representa un input type="number" nativo oculto para el envío numérico sin procesar y la validación nativa. Establece name, form, required, min, max y step en Root. form puede asociar el campo con un formulario en otra parte del documento. Los controles de ajuste predeterminados usan type="button", por lo que los pasos no envían el formulario.
disabled impide la interacción y excluye el valor del envío. readOnly impide los cambios y mantiene la entrada visible enfocables y su valor de formulario disponible. Usa un valor controlado cuando la aplicación deba restablecer el estado numérico; el restablecimiento nativo del formulario no lo restablece.
Destinos DOM y personalización
Los atributos nativos,
className, style y render se dirigen a la parte que los recibe. La personalización de la entrada se aplica al control visible; la personalización del contenedor pertenece a Root o Group. Para enfocar el control, usa Input.ref en lugar de Root.inputRef.
Cada parte acepta un elemento o callback mediante render, con el tipo de estado público correspondiente. Reenvía las props y la ref proporcionadas al elemento DOM adecuado para que la edición, el enfoque, las etiquetas y la validación sigan funcionando. Cuando un control de pasos representa un elemento que no es un botón, establece nativeButton={false}. className y style también aceptan callbacks de estado. El estado incluye value numérico, inputValue con formato, required, disabled, readOnly, scrubbing y el estado de Field heredado.
Los puntos de entrada públicos exportan las props y el tipo de estado de cada parte, además de NumberFieldRootChangeEventDetails, NumberFieldRootChangeEventReason, NumberFieldRootCommitEventDetails y NumberFieldRootCommitEventReason.
Renderizador del componente Front
Los dispositivos de prueba de sandbox de React y Preact verifican el formato inicial de configuración regional, el pegado localizado, los valores numéricos sin procesar de formularios, las etiquetas accesibles, las refs, la composición de renderizado, las confirmaciones al perder el foco, los detalles de cambio y confirmación mediante teclado, y los detalles de cambio mediante puntero. La escritura secuencial después de borrar un campo localizado controlado actualmente restablece el cursor en el renderizador: escribir2 y luego 3 puede producir 32. Un ajuste de puntero con formato también puede competir con la pérdida de foco y dejar la entrada visible mostrando el valor anterior. Los ajustes mediante puntero informan cambios, pero al soltar el puntero no se entrega el callback de confirmación correspondiente; en su lugar, una pérdida de foco posterior puede confirmar con input-blur. Arrastrar el área de arrastre y usar su cursor personalizado tampoco están disponibles en el sandbox. Estas limitaciones no afectan a los hosts habituales de React.
”Props”
La referencia se genera a partir de los tipos de componentes públicos instalados. Los atributos nativos y los controladores de eventos también se aceptan en las partes que representan elementos.NumberField.Root
boolean
predeterminado:"false"
Allows typed, pasted, and autofilled values outside min and max. Native range validation still applies; step interactions remain bounded.
boolean
predeterminado:"false"
Allows wheel adjustments while the visible input is focused and hovered. Defaults to false.
ReactNode
Composed NumberField parts and supporting content.
string | ((state: NumberFieldRootState) => string | undefined)
Class applied to this part, or a callback receiving its NumberField state.
number
predeterminado:"empty"
Initial uncontrolled number. Omit to start empty; the public type accepts a number.
boolean
predeterminado:"false"
Prevents interaction and excludes the value from form submission.
string
ID of the form owning the hidden native number input.
NumberFormatOptions
Intl.NumberFormat options for display and parsing, including currency, units, percent, grouping, and precision. Explicit rounding options can normalize the committed value on blur.
string
ID associated with the visible input. Generated when omitted.
Ref<HTMLInputElement>
Ref to the hidden native number input used for submission and validation. Use Input.ref to focus the visible text input.
number
predeterminado:"10"
Amount used while Shift is held. Defaults to 10.
LocalesArgument
Locale or locale list used to format and parse numbers. Defaults to the runtime locale.
number
Inclusive maximum for stepping and native range validation.
number
Inclusive minimum for stepping and native range validation.
string
Name of the raw numeric value submitted by the hidden input.
((value: number | null, eventDetails: NumberFieldRootChangeEventDetails) => void)
Receives the next number or null and change details with the native event, reason, cancellation and propagation methods, and optional stepping direction.
((value: number | null, eventDetails: NumberFieldRootCommitEventDetails) => void)
Receives the committed number or null and generic details containing event and reason. Typing commits on blur; pointer steps and scrubbing commit on release; keyboard and wheel changes commit immediately.
boolean
predeterminado:"false"
Prevents changes while keeping the visible input focusable.
Ref<HTMLDivElement>
Ref to the root div, or the element composed through Root.render.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, NumberFieldRootState>
Composes this part with an element or render callback. Forward the supplied props and ref to the corresponding DOM element.
boolean
predeterminado:"false"
Requires a numeric value for native form submission.
number
predeterminado:"0.1"
Amount used while Alt is held. Defaults to 0.1.
boolean
predeterminado:"false"
Snaps step interactions to multiples of the active step. Defaults to false.
number | "any"
predeterminado:"1"
Base amount for buttons, arrow keys, wheel, and scrubbing. Use any to disable native step validation while stepping by 1.
CSSProperties | ((state: NumberFieldRootState) => CSSProperties | undefined)
Inline styles applied to this part, or a callback receiving its NumberField state.
number | null
Controlled raw numeric value. Use null for an empty field.
NumberField.Group
ReactNode
The visible input and any increment or decrement controls.
string | ((state: NumberFieldGroupState) => string | undefined)
Class applied to this part, or a callback receiving its NumberField state.
Ref<HTMLDivElement>
Ref to the group div, or the element composed through Group.render.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, NumberFieldGroupState>
Composes this part with an element or render callback. Forward the supplied props and ref to the corresponding DOM element.
CSSProperties | ((state: NumberFieldGroupState) => CSSProperties | undefined)
Inline styles applied to this part, or a callback receiving its NumberField state.
NumberField.Input
string
predeterminado:"Number field"
Describes the role to assistive technology. Defaults to Number field; use Field.Label, aria-label, or aria-labelledby for the accessible name.
string | ((state: NumberFieldInputState) => string | undefined)
Class applied to this part, or a callback receiving its NumberField state.
Ref<HTMLInputElement>
Ref to the visible native text input.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>, NumberFieldInputState>
Composes the visible text input with an element or render callback. Forward the supplied props and ref to an input. Customize layout through Root or Group.
number
Native input size attribute. Use styles to customize visual dimensions.
CSSProperties | ((state: NumberFieldInputState) => CSSProperties | undefined)
Inline styles applied to this part, or a callback receiving its NumberField state.
NumberField.Increment
ReactNode
Visible content for the increment control. Supply its accessible name.
string | ((state: NumberFieldIncrementState) => string | undefined)
Class applied to this part, or a callback receiving its NumberField state.
boolean
predeterminado:"true"
Whether render composes a native button. Set false for a custom non-button element so Base UI supplies button interaction.
Ref<HTMLButtonElement>
Ref to the increment button, or the element composed through render.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, NumberFieldIncrementState>
Composes this part with an element or render callback. Forward the supplied props and ref to the corresponding DOM element.
CSSProperties | ((state: NumberFieldIncrementState) => CSSProperties | undefined)
Inline styles applied to this part, or a callback receiving its NumberField state.
NumberField.Decrement
ReactNode
Visible content for the decrement control. Supply its accessible name.
string | ((state: NumberFieldDecrementState) => string | undefined)
Class applied to this part, or a callback receiving its NumberField state.
boolean
predeterminado:"true"
Whether render composes a native button. Set false for a custom non-button element so Base UI supplies button interaction.
Ref<HTMLButtonElement>
Ref to the decrement button, or the element composed through render.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, NumberFieldDecrementState>
Composes this part with an element or render callback. Forward the supplied props and ref to the corresponding DOM element.
CSSProperties | ((state: NumberFieldDecrementState) => CSSProperties | undefined)
Inline styles applied to this part, or a callback receiving its NumberField state.
NumberField.ScrubArea
ReactNode
Content the user can drag to adjust the number, plus an optional ScrubAreaCursor.
string | ((state: NumberFieldScrubAreaState) => string | undefined)
Class applied to this part, or a callback receiving its NumberField state.
"horizontal" | "vertical"
predeterminado:"horizontal"
Pointer movement direction used for scrubbing.
number
predeterminado:"2"
Pixels of pointer movement needed for a step. Larger values reduce sensitivity.
Ref<HTMLSpanElement>
Ref to the scrub area span, or the element composed through render.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, NumberFieldScrubAreaState>
Composes this part with an element or render callback. Forward the supplied props and ref to the corresponding DOM element.
CSSProperties | ((state: NumberFieldScrubAreaState) => CSSProperties | undefined)
Inline styles applied to this part, or a callback receiving its NumberField state.
number
Optional distance from the scrub area center at which the pointer loops around.
NumberField.ScrubAreaCursor
ReactNode
Custom cursor content shown during supported pointer-lock scrubbing.
string | ((state: NumberFieldScrubAreaCursorState) => string | undefined)
Class applied to this part, or a callback receiving its NumberField state.
Ref<HTMLSpanElement>
Ref to the cursor span portaled to the document body while active. Null while absent.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, NumberFieldScrubAreaCursorState>
Composes this part with an element or render callback. Forward the supplied props and ref to the corresponding DOM element.
CSSProperties | ((state: NumberFieldScrubAreaCursorState) => CSSProperties | undefined)
Inline styles applied to this part, or a callback receiving its NumberField state.