3

我正在使用 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;

知道如何使用验证错误滚动到第一个输入。

4

2 回答 2

4
                             <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>

这是使用 Formik 在大表单中滚动到第一个错误时最简单的方法,我在 Formik 提交按钮中执行此操作,其中errors对象和submitForm()函数来自 Formik

于 2021-04-01T05:47:56.887 回答
0

我认为您可以保存出现错误的输入参考,并且可以滚动到该参考,您可以参考认为

于 2020-04-15T15:48:10.110 回答