ข้ามไปยังเนื้อหา

ช่องรหัส OTP

OtpInput

A one-time code in separate boxes. A digit moves focus on, Backspace in an empty box moves back, and pasting a whole code fills the boxes from the one in focus. label names the group of boxes.

ใช้กรอกรหัสยืนยันครั้งเดียวที่ส่งทาง SMS หรืออีเมล ตัวเลขแต่ละหลักอยู่ในช่องของตัวเอง และวางรหัสทั้งชุดได้ label แสดงเหนือช่องและเป็นชื่อของกลุ่มช่อง สำหรับรหัสผ่าน ใช้ PasswordInput

import { OtpInput } from "@bsru/ui";

ตัวอย่าง

รหัส 6 หลัก

label จำเป็นต้องส่ง hint บอกว่าส่งรหัสไปที่ใด onValueChange ได้ตัวเลขที่พิมพ์แล้วต่อกัน

รหัสยืนยันครั้งเดียว

ส่งไปที่เบอร์ 08X-XXX-5678 แล้ว

<OtpInput
  label="รหัสยืนยันครั้งเดียว"
  hint="ส่งไปที่เบอร์ 08X-XXX-5678 แล้ว"
  onValueChange={handleValueChange}
/>

รหัส 4 หลัก

length กำหนดจำนวนช่อง

รหัสยืนยัน

<OtpInput
  length={4}
  label="รหัสยืนยัน"
  onValueChange={handleValueChange}
/>

รหัสไม่ถูกต้อง

error แสดงใต้ช่องและทำให้ทุกช่องเป็นสีผิดพลาด บอกว่าทำอะไรต่อ

รหัสยืนยันครั้งเดียว

รหัสไม่ถูกต้องหรือหมดอายุแล้ว ขอรหัสใหม่แล้วลองอีกครั้ง

<OtpInput
  label="รหัสยืนยันครั้งเดียว"
  error="รหัสไม่ถูกต้องหรือหมดอายุแล้ว ขอรหัสใหม่แล้วลองอีกครั้ง"
  onValueChange={handleValueChange}
/>

props ทั้งหมด

ตัวอย่างด้านบนใช้ props เพียงบางตัว ตารางนี้แสดงทุกตัวที่คอมโพเนนต์รับ พร้อมค่าเริ่มต้นและค่าที่ใช้ได้

OtpInput props
ชื่อชนิดข้อมูลค่าเริ่มต้นคำอธิบาย
hintstring—Help under the field, such as the format or a limit.
errorstring—What's wrong and how to fix it, shown under the field. It marks the field invalid.
lengthnumber6How many digits the code has.
label* จำเป็นstring—The visible label, which also names the group of boxes, such as รหัสยืนยันครั้งเดียว.
valuestring—The digits, when the screen keeps them, such as "" to clear the boxes after a wrong code.
onValueChange(code: string) => void—Hears the digits typed so far, joined, on each change.

ข้อควรปฏิบัติ

  • ส่งรหัสเพื่อตรวจเมื่อ onValueChange ได้ครบตามจำนวนหลัก ไม่ต้องมีปุ่มยืนยันแยก
  • แป้นพิมพ์: พิมพ์ตัวเลขแล้วโฟกัสไปช่องถัดไป Backspace ในช่องว่างกลับไปช่องก่อนหน้า การวางรหัสเติมทุกช่องจากช่องที่โฟกัส
  • บอกว่าส่งรหัสไปที่ใด โดยซ่อนบางส่วนของเบอร์หรืออีเมล และมีวิธีขอรหัสใหม่

ซอร์สโค้ด: ui/src/special-inputs.tsx