use-otp-input
Version:
🚀 Awesome React Hook for One-time password (OTP) Input
40 lines (39 loc) • 1.56 kB
TypeScript
export interface UseOTPInputOptions {
/** 默认值:6 */
length?: number;
/** onChange 之前回调,可用于标准化 value */
normalizeValue?: (value: string, previousValue: string) => string;
value?: string;
onChange?: (value: string) => void;
}
/**
* React Hook for One Time Password Input / 一次性密码输入框 React Hook
*
* 主要模拟常规 Input 组件,使得输入更符合直觉,包括以下核心用例:
*
* - 支持符合 Input 组件直觉的*输入*逻辑,包括粘贴文本字符串
* - 支持 Backspace 和 Delete 及其快捷键操作
* - 支持左右方向键跳转输入位置
*
* 已知不支持的操作用例:
*
* - 字符多选操作
* - 不支持 Backspace 和 Delete 长按连续删除字符串
*/
export default function useOTPInput(options?: UseOTPInputOptions): {
inputProps: {
ref: (ref: HTMLInputElement | null) => void;
value: string;
onChange: (event: import("react").ChangeEvent<HTMLInputElement>) => void;
onFocus: (event: import("react").FocusEvent<HTMLInputElement, Element>) => void;
onKeyDown: (event: import("react").KeyboardEvent<HTMLInputElement>) => void;
/**
* 实测发现 onKeyDown 时 selectionStart 是按下前的位置,
* onKeyUp 时 selectionStart 是按下后的位置
*/
onKeyUp: (event: import("react").KeyboardEvent<HTMLInputElement>) => void;
}[];
clearInput: () => void;
setInput: (nextValue: string) => void;
getInput: () => string;
};