我正在使用 Material UI 和打字稿做出反应并有一个表格。在提交表单时,如果输入有验证错误,我想滚动到第一个出现验证错误的输入。我在下面粘贴了简单的表单代码,它在提交时在城镇输入中注入验证错误。实际上,错误可能出现在任何或多个输入中。
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;
知道如何使用验证错误滚动到第一个输入。