Tengo el componente PhoneConformition que usa input:
<Flexbox> {CODE_INPUTS.map((input, index) => ( <Controller key={input.name} name={input.name} control={control} defaultValue="" // rules={{ required: true }} render={(props) => ( <InputCode {...props} ref={inputListRefs.current[index]} className={styles.phoneConfirmation__formInput} onValueSet={() => handleOnValueSet(index)} /> )} // props contains: onChange, onBlur and value /> ))} </Flexbox>Donde CódigoEntrada es =
type Props = { className?: string; name: string; onChange: (...event: any[]) => void; onValueSet: (value: string) => void; }; const InputCode = forwardRef<HTMLInputElement, Props>( ({ className, name, onChange, onValueSet }, ref) => { const classNames = [styles.inputCode, className].join(" "); const [valueState, setValueState] = useState<string>(""); const handleChange = (event: React.SyntheticEvent<HTMLInputElement>) => { event.preventDefault(); }; const handleKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => { const value: number = parseInt(event.key, 10); if (!isNaN(value)) { const valueString: string = value.toString(); setValueState(valueString); onChange(valueString); onValueSet(valueString); } }; return ( <div className={classNames}> <input ref={ref} name={name} className={styles.inputCode__input} type="text" onChange={handleChange} onKeyPress={handleKeyPress} value={valueState} /> </div> ); } ); export default InputCode;PERO si quiero usar la función en la función de conjunto de valores donde se enfoca en otra función de acuerdo con el índice. Todo funciona en lugar de .focus
const handleOnValueSet = (index: number) => { const formvalues = getValues(); onCodeChange(formvalues); if (index + 1 < CODE_INPUTS.length) { inputListRefs.current[index + 1].current?.focus(); } }.focus no funciona con onValueSet, sin embargo, onChange o onKeyDown funcionan correctamente.
Encontré la solución. El problema era que la segunda llamada onCodeChange comenzó antes de que terminara la primera.
Acabo de agregar un setTimeOut de 10 ms en la segunda llamada y funcionó.
Gracias a todos