typescript - Reactjs Zum ersten Fehler scrollen beim Absenden eines großen Formulars
Ich verwende React mit Material UI und TypeScript und habe ein Formular. Beim Absenden des Formulars möchte ich, dass, wenn Eingaben Validierungsfehler haben, zum ersten Eingabefeld mit dem Validierungsfehler gescrollt wird. Ich habe den einfachen Formularcode unten eingefügt, der beim Absenden einen Validierungsfehler im Ort-Eingabefeld erzeugt. In Wirklichkeit könnte der Fehler in einem oder mehreren Eingabefeldern auftreten.
import React, { useState, FormEvent } from 'react';
import { Grid, TextField, Button } from '@material-ui/core';
const ScrollTest = () => {
const [state, setState] = useState<{ town: string; county: string }>({
town: '',
county: '',
});
const [error, setError] = useState({ town: '', county: '' });
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { name, value } = e.target;
const errorVal = !value ? `${name} is requied` : '';
setState({ ...state, [name]: value });
setError({ ...error, [name]: errorVal });
};
const handleSubmit = (e: FormEvent) => {
e.preventDefault();
if (!state.town) {
setError({ ...error, town: 'Town input is required' });
}
};
return (
<>
<form onSubmit={(e) => handleSubmit(e)} noValidate>
<Grid container justify='center' alignItems='center' spacing={2}>
<Grid item xs={12} md={6}>
<TextField
error={!!error.town}
variant='outlined'
fullWidth
id='town'
label='Town'
name='town'
autoComplete='town'
placeholder='Town *'
value={state.town || ''}
onChange={handleChange}
helperText={error.town}
/>
</Grid>
</Grid>
<Grid container justify='center' alignItems='center' spacing={2}>
<Grid item xs={12} md={6}>
<TextField
error={!!error.county}
variant='outlined'
fullWidth
id='county'
label='County'
name='county'
autoComplete='county'
placeholder='County'
value={state.county || ''}
onChange={handleChange}
helperText={error.county}
/>
</Grid>
</Grid>
<Grid container justify='center' alignItems='center' spacing={2}>
<Grid item xs={12} md={6}>
<TextField
variant='outlined'
fullWidth
id='county2'
label='County2'
name='county2'
autoComplete='county2'
placeholder='County2'
value={state.county || ''}
onChange={handleChange}
/>
</Grid>
</Grid>
<br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br>{' '}
<br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br>{' '}
<br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br>{' '}
<br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br>{' '}
<br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br>{' '}
<br></br> <br></br> <br></br>
<Grid container justify='center' alignItems='center'>
<Grid item xs={12} md={6}>
<Button type='submit' fullWidth variant='contained' color='primary'>
Update profile
</Button>
</Grid>
</Grid>
</form>
</>
);
};
export default ScrollTest;
Irgendeine Ahnung, wie man zum ersten Eingabefeld mit dem Validierungsfehler scrollt.
Antwort #1
<Button
disabled={isSubmitting}
variant="contained"
color="primary"
onClick={() => {
const err = Object.keys(errors);
if (err.length) {
const input = document.querySelector(
`input[name=${err[0]}]`
);
input.scrollIntoView({
behavior: 'smooth',
block: 'center',
inline: 'start',
});
}
submitForm();
}}
>
{isSubmitting ? (
<CircularProgress size={22} />
) : (
'Submit'
)}
</Button>
Dies ist das einfachste, was Sie tun können, um in einem großen Formular mit Formik zum ersten Fehler zu scrollen. Ich habe dies innerhalb des Formik-Absendebuttons gemacht, wobei das errors-Objekt und die Funktion submitForm() von Formik stammen.
Antwort #2
Eine andere Möglichkeit, dies einfach zu tun, ist die Verwendung von React Hook Form
Und verwenden Sie die Option shouldFocusError, wenn Sie den useForm-Hook initialisieren
Zum Beispiel:
const { register, handleSubmit } = useForm({ shouldFocusError: true })
