Input OTP
InputOtp 组件让用户可以输入一次性密码 (OTP)。它构建于 @guilherme_rodz 开发的 input-otp 库之上。
安装
The above command is for individual installation only. You may skip this step if @heroui/react is already installed globally.
导入
用法
禁用 (Disabled)
isDisabled 属性会禁用用户与 InputOtp 组件的交互。
只读 (Read Only)
isReadOnly 属性使 InputOtp 组件变为只读,同时保持其视觉外观。
必填 (Required)
isRequired 属性将 InputOtp 标记为必填字段。
尺寸 (Sizes)
InputOtp 的大小可以使用 size 属性自定义。默认值为 md。
颜色 (Colors)
InputOtp 的颜色可以通过 color 属性更改。
变体 (Variants)
InputOtp 的样式/变体可以通过 variant 属性更改。默认情况下,variant 属性设置为 flat。
圆角 (Radius)
InputOtp 的圆角可以通过 radius 属性更改。默认情况下,radius 属性设置为 md。
密码 (Password)
通过将 type 设置为 password,InputOtp 可用作密码/安全 PIN 码输入框。
描述 (Description)
InputOtp 的描述可以通过 description 属性设置。
错误信息 (Error Message)
InputOtp 的自定义错误信息可以通过 errorMessage 属性设置。
允许的按键 (Allowed Keys)
InputOtp组件只接受指定的输入按键,任何其他输入将被忽略。- 您可以使用
allowedKeys属性自定义允许的按键,它接受一个正则表达式模式。 - 默认情况下,
allowedKeys设置为^[0-9]*$(仅限数字)。
受控模式 (Controlled)
React Hook Form
您可以将 InputOtp 与 React Hook Form 结合使用,以进行表单验证和提交处理。
不同长度与验证 (Different Lengths & Validation)
InputOtp 组件通过 length 属性支持不同的长度。您可以通过向 length 属性传递一个数字值来设置输入段的数量。常见的用例包括 4 位 PIN 码和 6 位验证码。
自定义样式 (Custom Styles)
您可以使用 classNames 属性自定义 InputOtp 组件的样式。
插槽 (Slots)
- base: InputOtp 包装器,处理对齐、位置和整体外观。
- wrapper: 包装底层 input-otp 组件。作为
containerClassName属性传递给底层 input-otp 组件。 - input: 输入元素。
- segmentWrapper: 包装所有段元素。
- segment: 段元素。
- caret: 光标,表示 input-otp 组件的输入指示器。
- passwordChar: 密码字符,表示输入类型为 password 时的文本样式。
- helperWrapper: 包装
description和errorMessage。 - description: input-otp 的描述。
- errorMessage: input-otp 的错误信息。
数据属性 (Data Attributes)
InputOtp 在 base 元素上具有以下属性:
- data-invalid:
当 input-otp 无效时。基于
isInvalid属性。 - data-required:
当 input-otp 为必填时。基于
isRequired属性。 - data-readonly:
当 input-otp 为只读时。基于
isReadOnly属性。 - data-filled: 当 input-otp 完全填满时。
- data-disabled:
当 input-otp 被禁用时。基于
isDisabled属性。
InputOtp 在 segment 元素上还具有以下属性:
- data-active: 当该段处于激活状态时。
- data-focus: 当该段获得焦点时。
- data-focus-visible: 当该段获得焦点且可见时。
- data-has-value: 当该段有值时。
可访问性 (Accessibility)
- 构建于 input-otp 之上。
- 通过 ARIA 向辅助技术暴露必填和无效状态。
- 支持通过 ARIA 将描述和错误信息帮助文本链接到 input-otp。
- 键盘导航:
- Tab: 在输入段之间移动焦点
- 方向键: 在段之间导航
- Backspace: 清除当前段并将焦点移动到前一段
- ARIA 属性:
aria-invalid: 指示验证状态aria-required: 指示输入是否为必填
API
InputOtp 属性
| Prop | Type | Default |
length | | "4" |
allowedKeys | | "^[0-9]*$" |
variant | | "flat" |
color | | "default" |
size | | "md" |
radius | | |
value | | |
defaultValue | | |
description | | |
errorMessage | | |
fullWidth | | false |
isRequired | | false |
isReadOnly | | false |
isDisabled | | false |
isInvalid | | false |
baseRef | | |
disableAnimation | | false |
classNames | | |
autoFocus | | false |
textAlign | | "center" |
pushPasswordManagerStrategy | | |
pasteTransformer | | |
containerClassName | | |
noScriptCSSFallback | |
InputOtp 事件
| Prop | Type | Default |
onChange | | |
onValueChange | | |
onComplete | |

