#javascript #html #reactjs #react-hook-form
#javascript #HTML #reactjs #реагировать-перехват-форма
Вопрос:
я хочу спросить, возможно ли автоматическое выполнение в форме без нажатия на входные данные. У меня есть входные данные для проверки кода, и на самом деле мне нужно щелкнуть на входе, чтобы записать число, одно за другим. Я хотел бы посмотреть, может ли это выполняться автоматически. На данный момент 1 число было записано в 1 ввод, он должен автоматически сфокусировать следующий ввод. Кто-нибудь может мне помочь в этом?
вот мой компонент:
/* eslint-disable jsx-a11y/anchor-is-valid */
/* eslint-disable jsx-a11y/alt-text */
import React, { useContext } from "react";
import { useForm } from "react-hook-form";
import { Link, useHistory } from 'react-router-dom';
import { AuthContext } from '../../../states/contexts/authContext';
import { maxLengthCheck } from '../../../helpers/FunctionsTools';
export const CodeVerificationForm = () => {
const history = useHistory();
const { register, handleSubmit, formState } = useForm();
const { /* loading,*/ errorMessage, codeVerificationContext } = useContext(
AuthContext
);
const handlVerificationSend = async(data) => {
const credentials = {
username: localStorage.getItem('username'),
pin: data.digit1 data.digit2 data.digit3 data.digit4,
};
try {
const response = await codeVerificationContext(credentials);
if (response) {
return history.push('/login/reset-password');
}
} catch(error) {
//console.log(error)
}
}
return (
<div className="form-login-container">
<div className="forgot-form-title-container mb-4">
<h1 className="large-title-1 text-center">Verification Code</h1>
</div>
<p className="text-center forgot-subtitle-text">We sent a 4 digit verification code to your email <br /> please enter the code below.</p>
<form onSubmit={handleSubmit(handlVerificationSend)}>
<div className="code-group text-center">
<input name="digit1" type="number" className="form-control" maxLength={1} onInput={maxLengthCheck} ref={register({ required: true })} />
<input name="digit2" type="number" className="form-control" maxLength={1} onInput={maxLengthCheck} ref={register({ required: true })} />
<input name="digit3" type="number" className="form-control" maxLength={1} onInput={maxLengthCheck} ref={register({ required: true })} />
<input name="digit4" type="number" className="form-control" maxLength={1} onInput={maxLengthCheck} ref={register({ required: true })} />
</div>
{errorMessage amp;amp; <div className="text-center"><small className="validation-text">Something is wrong!</small></div>}
<div className="text-center mb-5 mt-5">
<button
type="submit"
className={`btn w-100 ${formState.dirtyFields.digit1 amp;amp; formState.dirtyFields.digit2 amp;amp; formState.dirtyFields.digit3 amp;amp; formState.dirtyFields.digit4 ? "orange-custom-button" : "disabled-custom-button"}`}
disabled={formState.dirtyFields.digit1 amp;amp; formState.dirtyFields.digit2 amp;amp; formState.dirtyFields.digit3 amp;amp; formState.dirtyFields.digit4 ? '' : 'disabled'}>Send
</button>
<p className="text-center orange-link">Didn't receive it? <Link to="/login/forgot-password">Try Again</Link></p>
</div>
</form>
</div>
);
};
заранее спасибо.
Ответ №1:
maxLengthCheck
Проверьте, не является ли ввод, значение которого только что было изменено, последним дочерним элементом, и сфокусируйте nextElementSibling
Комментарии:
1. спасибо, я решаю эту проблему, следуя этой статье: linguinecode.com/post/focus-next-input-in-react
Ответ №2:
Решите, я следил за этой статьей, и моим результатом была эта функция:
const FocusNextInput = e => {
const { maxLength, value, name } = e.target;
const [ fieldName, fieldIndex ] = name.split("N");
// Check if they hit the max character length
if (value.length === maxLength) {
// Check if it's not the last input field
if (fieldIndex < 4) {
// Get the next input field
const nextSibling = document.querySelector(
`input[name=digitN${parseInt(fieldIndex, 4) 1}]`
);
// If found, focus the next field
if (nextSibling !== null) {
nextSibling.focus();
}
}
}
}
это работает с атрибутом onChange во входных данных.