/
GEOSHEV
/
Event-app
Обзор
Документация
Войти
/
GEOSHEV
/
Event-app
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
develop
src/components/ui/CodeInput/index.tsx
92 строки
2 KB
Gosha
feat: add verify screen, add detailed lesson card
19 май 2026, 19:45
19 май 2026, 19:45
77fad0f
Код
Авторство
О чём код?
import { useRef, useState } from "react"; import { NativeSyntheticEvent, TextInput, TextInputKeyPressEventData, View, } from "react-native"; import { styles } from "./styles"; interface CodeInputProps { length?: number; onComplete?: (code: string) => void; onChange?: (code: string) => void; } export const CodeInput = ({ length = 6, onComplete, onChange, }: CodeInputProps) => { const [values, setValues] = useState<string[]>(Array(length).fill("")); const inputsRef = useRef<(TextInput | null)[]>([]); const handleChange = (text: string, index: number) => { // Handle paste of full code if (text.length > 1) { const digits = text.replace(/\D/g, "").slice(0, length).split(""); const newValues = Array(length).fill(""); digits.forEach((d, i) => { newValues[i] = d; }); setValues(newValues); onChange?.(newValues.join("")); const nextIndex = Math.min(digits.length, length - 1); inputsRef.current[nextIndex]?.focus(); if (digits.length === length) { onComplete?.(newValues.join("")); } return; } const digit = text.replace(/\D/g, ""); const newValues = [...values]; newValues[index] = digit; setValues(newValues); onChange?.(newValues.join("")); if (digit && index < length - 1) { inputsRef.current[index + 1]?.focus(); } if ( newValues.every((v) => v !== "") && newValues.join("").length === length ) { onComplete?.(newValues.join("")); } }; const handleKeyPress = ( e: NativeSyntheticEvent<TextInputKeyPressEventData>, index: number, ) => { if (e.nativeEvent.key === "Backspace" && !values[index] && index > 0) { inputsRef.current[index - 1]?.focus(); } }; return ( <View style={styles.container}> {Array(length) .fill(null) .map((_, index) => ( <TextInput key={index} ref={(ref) => { inputsRef.current[index] = ref; }} style={[styles.cell, values[index] ? styles.cellFilled : null]} value={values[index]} onChangeText={(text) => handleChange(text, index)} onKeyPress={(e) => handleKeyPress(e, index)} keyboardType="number-pad" maxLength={length} // allows paste textAlign="center" autoFocus={index === 0} selectionColor="#4F8EF7" /> ))} </View> ); };