import { NumberInput } from "@chakra-ui/react"
const Demo = () => {
return (
<NumberInput.Root defaultValue="10" width="200px">
<NumberInput.Control />
<NumberInput.Input />
</NumberInput.Root>
)
}
用法
¥Usage
import { NumberInput } from "@chakra-ui/react"
<NumberInput.Root>
<NumberInput.Label />
<NumberInput.ValueText />
<NumberInput.Control>
<NumberInput.IncrementTrigger />
<NumberInput.DecrementTrigger />
</NumberInput.Control>
<NumberInput.Scrubber />
<NumberInput.Input />
</NumberInput.Root>
如果你更喜欢封闭的组件组合,请查看 以下代码片段。
¥If you prefer a closed component composition, check out the snippet below.
快捷键
¥Shortcuts
NumberInput
组件提供了一组常见用例的快捷方式。
¥The NumberInput
component provides a set of shortcuts for common use cases
NumberInputControl
此组件默认渲染其中的 NumberInput.IncrementTrigger
和 NumberInput.DecrementTrigger
。
¥This component renders the NumberInput.IncrementTrigger
and
NumberInput.DecrementTrigger
within it by default.
正在写入:
¥Writing this:
<NumberInput.Control />
如果你不需要自定义触发器,以下代码是简写:
¥is shorthand for writing this if you don't need to customize the triggers:
<NumberInput.Control>
<NumberInput.IncrementTrigger />
<NumberInput.DecrementTrigger />
</NumberInput.Control>
示例
¥Examples
尺寸
¥Sizes
将 size
属性传递给 NumberInput.Root
组件,即可更改数字输入框的大小。
¥Pass the size
prop to the NumberInput.Root
component to change the size of
the number input.
import { For, NumberInput, Stack } from "@chakra-ui/react"
const Demo = () => {
return (
<Stack gap="5" width="200px">
<For each={["xs", "sm", "md", "lg"]}>
{(size) => (
<NumberInput.Root size={size} key={size} defaultValue="10">
<NumberInput.Control />
<NumberInput.Input />
</NumberInput.Root>
)}
</For>
</Stack>
)
}
格式化
¥Formatting
将 formatOptions
属性传递给 NumberInput.Root
组件,以格式化数字输入值。此值映射到 Intl.NumberFormatOptions
,并根据当前语言环境应用。
¥Pass the formatOptions
prop to the NumberInput.Root
component to format the
number input value. The value of this maps to Intl.NumberFormatOptions
and is
applied based on the current locale.
import { NumberInput, Stack } from "@chakra-ui/react"
const Demo = () => {
return (
<Stack gap="5" maxW="200px">
<NumberInput.Root
defaultValue="5"
step={0.01}
formatOptions={{
style: "percent",
}}
>
<NumberInput.Control />
<NumberInput.Input />
</NumberInput.Root>
<NumberInput.Root
defaultValue="45"
formatOptions={{
style: "currency",
currency: "EUR",
currencyDisplay: "code",
currencySign: "accounting",
}}
>
<NumberInput.Control />
<NumberInput.Input />
</NumberInput.Root>
<NumberInput.Root
defaultValue="4"
formatOptions={{
style: "unit",
unit: "inch",
unitDisplay: "long",
}}
>
<NumberInput.Control />
<NumberInput.Input />
</NumberInput.Root>
</Stack>
)
}
最小和最大
¥Min and Max
将 min
和 max
属性传递给 NumberInput.Root
组件,以设置数字输入的最小值和最大值。
¥Pass the min
and max
props to the NumberInput.Root
component to set the
minimum and maximum values of the number input.
如果输入的值小于 min
或大于 max
,则在模糊或按下 Enter 键时,该值将被限制到最近的边界。
¥If value entered is less than min
or greater than max
, the value will be
clamped to the nearest boundary on blur, or enter key press.
import { NumberInput } from "@chakra-ui/react"
const Demo = () => {
return (
<NumberInput.Root width="200px" defaultValue="10" min={5} max={50}>
<NumberInput.Control />
<NumberInput.Input />
</NumberInput.Root>
)
}
步骤
¥Step
将 step
属性传递给 NumberInput.Root
组件,即可更改数字输入框的递增或递减间隔。
¥Pass the step
prop to the NumberInput.Root
component to change the increment
or decrement interval of the number input.
import { NumberInput } from "@chakra-ui/react"
const Demo = () => {
return (
<NumberInput.Root maxW="200px" defaultValue="2" step={3}>
<NumberInput.Control />
<NumberInput.Input />
</NumberInput.Root>
)
}
受控
¥Controlled
将 value
和 onValueChange
属性传递给 NumberInput.Root
组件,以控制数字输入的值。
¥Pass the value
and onValueChange
props to the NumberInput.Root
component
to control the value of the number input.
"use client"
import { NumberInput } from "@chakra-ui/react"
import { useState } from "react"
const Demo = () => {
const [value, setValue] = useState("10")
return (
<NumberInput.Root
maxW="200px"
value={value}
onValueChange={(e) => setValue(e.value)}
>
<NumberInput.Control />
<NumberInput.Input />
</NumberInput.Root>
)
}
移动步进器
¥Mobile Stepper
以下示例展示了如何将数字输入框组合为移动端步进器。
¥Here's an example of how to compose the number input as a mobile stepper.
import { HStack, IconButton, NumberInput } from "@chakra-ui/react"
import { LuMinus, LuPlus } from "react-icons/lu"
const Demo = () => {
return (
<NumberInput.Root defaultValue="3" unstyled spinOnPress={false}>
<HStack gap="2">
<NumberInput.DecrementTrigger asChild>
<IconButton variant="outline" size="sm">
<LuMinus />
</IconButton>
</NumberInput.DecrementTrigger>
<NumberInput.ValueText textAlign="center" fontSize="lg" minW="3ch" />
<NumberInput.IncrementTrigger asChild>
<IconButton variant="outline" size="sm">
<LuPlus />
</IconButton>
</NumberInput.IncrementTrigger>
</HStack>
</NumberInput.Root>
)
}
鼠标滚轮
¥Mouse Wheel
将 allowMouseWheel
属性传递给 NumberInput.Root
组件,以启用或禁用鼠标滚轮切换。
¥Pass the allowMouseWheel
prop to the NumberInput.Root
component to enable or
disable the mouse wheel to change
import { NumberInput } from "@chakra-ui/react"
const Demo = () => {
return (
<NumberInput.Root defaultValue="10" width="200px" allowMouseWheel>
<NumberInput.Control />
<NumberInput.Input />
</NumberInput.Root>
)
}
已禁用
¥Disabled
将 disabled
属性传递给 NumberInput.Root
组件,即可禁用数字输入。
¥Pass the disabled
prop to the NumberInput.Root
component to disable the
number input.
import { NumberInput } from "@chakra-ui/react"
const Demo = () => {
return (
<NumberInput.Root defaultValue="10" width="200px" disabled>
<NumberInput.Control />
<NumberInput.Input />
</NumberInput.Root>
)
}
无效
¥Invalid
使用 Field
组件和 invalid
属性指示数字输入无效。
¥Use the Field
component and the invalid
prop to indicate that the number
input is invalid.
import { Field, NumberInput } from "@chakra-ui/react"
const Demo = () => {
return (
<Field.Root invalid>
<Field.Label>Enter Number</Field.Label>
<NumberInput.Root defaultValue="10" width="200px">
<NumberInput.Control />
<NumberInput.Input />
</NumberInput.Root>
<Field.ErrorText>The entry is invalid</Field.ErrorText>
</Field.Root>
)
}
辅助文本
¥Helper Text
组合 Field
和 Field.HelperText
组件,为数字输入框添加辅助文本。
¥Compose the Field
and Field.HelperText
components to add helper text to the
number input.
import { Field, NumberInput } from "@chakra-ui/react"
const Demo = () => {
return (
<Field.Root>
<Field.Label>Enter Number</Field.Label>
<NumberInput.Root width="200px">
<NumberInput.Control />
<NumberInput.Input />
</NumberInput.Root>
<Field.HelperText>Enter a number between 1 and 10</Field.HelperText>
</Field.Root>
)
}
元素
¥Element
以下示例展示了如何使用输入组组件组合数字输入框,以便在左侧或右侧添加元素。
¥Here's an example of how to compose the number input with the input group component to add an element on either the left or right.
import { InputGroup, NumberInput } from "@chakra-ui/react"
import { LuDollarSign } from "react-icons/lu"
const Demo = () => {
return (
<NumberInput.Root defaultValue="10" width="200px">
<NumberInput.Control />
<InputGroup startElement={<LuDollarSign />}>
<NumberInput.Input />
</InputGroup>
</NumberInput.Root>
)
}
滑动条
¥Scrubber
使用 NumberInput.Scrubber
组件使数字输入支持滑动条交互。
¥Use the NumberInput.Scrubber
component to make the number input supports
scrubber interactions.
import { InputGroup, NumberInput } from "@chakra-ui/react"
import { LuArrowRightLeft } from "react-icons/lu"
const Demo = () => {
return (
<NumberInput.Root defaultValue="10" width="200px">
<NumberInput.Control />
<InputGroup
startElementProps={{ pointerEvents: "auto" }}
startElement={
<NumberInput.Scrubber>
<LuArrowRightLeft />
</NumberInput.Scrubber>
}
>
<NumberInput.Input />
</InputGroup>
</NumberInput.Root>
)
}
钩子表单
¥Hook Form
以下是如何将 NumberInput
组件与 react-hook-form
一起使用的示例。
¥Here is an example of how to use the NumberInput
component with
react-hook-form
.
"use client"
import { Button, Field, NumberInput } from "@chakra-ui/react"
import { zodResolver } from "@hookform/resolvers/zod"
import { Controller, useForm } from "react-hook-form"
import { z } from "zod"
const formSchema = z.object({
number: z.string({ message: "Number is required" }),
})
type FormValues = z.infer<typeof formSchema>
const Demo = () => {
const {
control,
handleSubmit,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(formSchema),
})
const onSubmit = handleSubmit((data) => console.log(data))
return (
<form onSubmit={onSubmit}>
<Field.Root invalid={!!errors.number}>
<Field.Label>Number</Field.Label>
<Controller
name="number"
control={control}
render={({ field }) => (
<NumberInput.Root
disabled={field.disabled}
name={field.name}
value={field.value}
onValueChange={({ value }) => {
field.onChange(value)
}}
>
<NumberInput.Control />
<NumberInput.Input onBlur={field.onBlur} />
</NumberInput.Root>
)}
/>
<Field.ErrorText>{errors.number?.message}</Field.ErrorText>
</Field.Root>
<Button size="sm" type="submit" mt="4">
Submit
</Button>
</form>
)
}
已关闭组件
¥Closed Component
以下是如何设置封闭组件组合的数字输入。
¥Here's how to setup the Number Input for a closed component composition.
import { NumberInput as ChakraNumberInput } from "@chakra-ui/react"
import * as React from "react"
export interface NumberInputProps extends ChakraNumberInput.RootProps {}
export const NumberInputRoot = React.forwardRef<
HTMLDivElement,
NumberInputProps
>(function NumberInput(props, ref) {
const { children, ...rest } = props
return (
<ChakraNumberInput.Root ref={ref} variant="outline" {...rest}>
{children}
<ChakraNumberInput.Control>
<ChakraNumberInput.IncrementTrigger />
<ChakraNumberInput.DecrementTrigger />
</ChakraNumberInput.Control>
</ChakraNumberInput.Root>
)
})
export const NumberInputField = ChakraNumberInput.Input
export const NumberInputScrubber = ChakraNumberInput.Scrubber
export const NumberInputLabel = ChakraNumberInput.Label
如果你想自动将封闭式组件添加到项目中,请运行以下命令:
¥If you want to automatically add the closed component to your project, run the command:
npx @chakra-ui/cli snippet add number-input
以下是如何使用它
¥Here's how to use the it
<NumberInputRoot>
<NumberInputField />
</NumberInputRoot>
属性
¥Props
根元素
¥Root
Prop | Default | Type |
---|---|---|
allowOverflow | true | boolean Whether to allow the value overflow the min/max range |
clampValueOnBlur | true | boolean Whether to clamp the value when the input loses focus (blur) |
focusInputOnChange | true | boolean Whether to focus input when the value changes |
inputMode | '\'decimal\'' | InputMode Hints at the type of data that might be entered by the user. It also determines the type of keyboard shown to the user on mobile devices |
locale | '\'en-US\'' | string The current locale. Based on the BCP 47 definition. |
max | 'Number.MAX_SAFE_INTEGER' | number The maximum value of the number input |
min | 'Number.MIN_SAFE_INTEGER' | number The minimum value of the number input |
pattern | '\'-?[0-9]*(.[0-9]+)?\'' | string The pattern used to check the <input> element's value against |
spinOnPress | true | boolean Whether to spin the value when the increment/decrement button is pressed |
step | '1' | number The amount to increment or decrement the value by |
colorPalette | 'gray' | 'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink' The color palette of the component |
size | 'md' | 'xs' | 'sm' | 'md' | 'lg' The size of the component |
variant | 'outline' | 'outline' | 'subtle' | 'flushed' The variant of the component |
as | React.ElementType The underlying element to render. | |
asChild | boolean Use the provided child element as the default rendered element, combining their props and behavior. For more details, read our Composition guide. | |
unstyled | boolean Whether to remove the component's style. | |
allowMouseWheel | boolean Whether to allow mouse wheel to change the value | |
defaultValue | string The initial value of the input when rendered. Use when you don't need to control the value of the input. | |
disabled | boolean Whether the number input is disabled. | |
form | string The associate form of the input element. | |
formatOptions | NumberFormatOptions The options to pass to the `Intl.NumberFormat` constructor | |
id | string The unique identifier of the machine. | |
ids | Partial<{
root: string
label: string
input: string
incrementTrigger: string
decrementTrigger: string
scrubber: string
}> The ids of the elements in the number input. Useful for composition. | |
invalid | boolean Whether the number input value is invalid. | |
name | string The name attribute of the number input. Useful for form submission. | |
onFocusChange | (details: FocusChangeDetails) => void Function invoked when the number input is focused | |
onValueChange | (details: ValueChangeDetails) => void Function invoked when the value changes | |
onValueInvalid | (details: ValueInvalidDetails) => void Function invoked when the value overflows or underflows the min/max range | |
readOnly | boolean Whether the number input is readonly | |
required | boolean Whether the number input is required | |
translations | IntlTranslations Specifies the localized strings that identifies the accessibility elements and their states | |
value | string The controlled value of the input |