0

我使用 FormGroup 和 FormControl(Material UI)创建了一个简单的表单(登录名和密码),一切正常,除了表单始终具有默认值(来自输入的最后一个有效值)

我使用 React.createRef 创建了两个 ref,并将它们分配给输入的 ref 属性,例如 ref={loginField},然后,在带有 [] 的 useEffect 中,我设置了所有值、支持字段的状态以及参考文献,如 loginField.current.value = '';

但是,它不起作用。似乎 loginField.current.value = '' 没有做任何事情。

这是我的表格

import React, { useEffect } from 'react';

import clsx from 'clsx';
import { makeStyles, withStyles } from '@material-ui/core/styles';
import IconButton from '@material-ui/core/IconButton';
import Input from '@material-ui/core/Input';
import InputAdornment from '@material-ui/core/InputAdornment';
import FormControl from '@material-ui/core/FormControl';
import { FormGroup } from '@material-ui/core';
import Visibility from '@material-ui/icons/Visibility';
import VisibilityOff from '@material-ui/icons/VisibilityOff';

const LOGIN = 'login';
const PASSWORD = 'password';

const useStyles = makeStyles(theme => ({
  root: {
    display: 'flex',
    flexWrap: 'wrap'
  },
  margin: {
    margin: theme.spacing(1)
  },
  withoutLabel: {
    marginTop: theme.spacing(1)
  }
}));

const StyledInput = withStyles({
  root: {
    '&$focused': {
      borderColor: '#B3B3B3'
    },
    '&$error': {
      borderColor: '#D33F49'
    },
    borderRadius: 30,
    border: '2px solid #CECECE',
    color: 'black',
    height: 50,
    padding: '20px 20px',
    backgroundColor: '#E8F0FE',
    fontFamily: 'Roboto',
    fontSize: 13,
    marginTop: '5px'
  },
  focused: {},
  error: {}
})(Input);

const Login = props => {
  const {
    submitVariant,
    dispatch
  } = props;

  const [values, setValues] = React.useState({
    login: '',
    password: ''
  });
  let loginField = React.createRef();
  let passwordField = React.createRef();
  const [fieldsErrors, setFieldsErrors] = React.useState({
    loginError: '',
    passwordError: ''
  });
  const [showPassword, setShowPassword] = React.useState(false);
  const classes = useStyles();

  const checkInputContent = (prop, newValue) => {
    switch (prop) {
      case LOGIN:
        if (newValue === '') {
          setFieldsErrors({
            ...fieldsErrors,
            loginError: 'Este campo es obligatorio'
          });
        } else if (newValue.length < 4) {
          setFieldsErrors({
            ...fieldsErrors,
            loginError: 'Un minimo de 4 caracteres es requerido'
          });
        } else {
          setFieldsErrors({
            ...fieldsErrors,
            loginError: ''
          });
        }
        break;
      case PASSWORD:
        if (newValue === '') {
          setFieldsErrors({
            ...fieldsErrors,
            passwordError: 'Este campo es obligatorio'
          });
        } else {
          setFieldsErrors({
            ...fieldsErrors,
            passwordError: ''
          });
        }
        break;
      default:
    }
  };

  const handleChange = prop => async event => {
    setValues({ ...values, [prop]: event.target.value });
    checkInputContent(prop, event.target.value);
  };

  const handleClickShowPassword = e => {
    e.preventDefault();
    setShowPassword(!showPassword);
  };

  const handleMouseDownPassword = event => {
    event.preventDefault();
  };

  useEffect(() => {
    setValues({ login: '', password: '' });
    setFieldsErrors({ loginError: '', passwordError: '' });
    loginField.current.value = '';
    passwordField.current.value = '';
  }, []);

  const clearFields = () => {
    setValues({ login: '', password: '' });
    setFieldsErrors({ loginError: '', passwordError: '' });
    loginField.current.value = '';
    passwordField.current.value = '';
  };

  const handleFocus = e => {

  };

  return (
    <Row className="justify-content-center align-items-center h-100">
      <Col md={4}>
        <MainLogo style={{ marginBottom: 30 }} />
        <FormGroup>
          <FormControl className={clsx(classes.margin, classes.textField)}>
            <StyledInput
              id={LOGIN}
              type="text"
              value={values.login}
              disableUnderline={true}
              placeholder="Email personal o RUT"
              ref={loginField}
              onFocus={handleFocus}
              error={fieldsErrors.loginError !== ''}
              onChange={handleChange(LOGIN)}
            />
          </FormControl>
          {fieldsErrors.loginError && <p style={styles.errorStyle}>{fieldsErrors.loginError}</p>}
          <FormControl className={clsx(classes.margin, classes.textField)}>
            <StyledInput
              id={PASSWORD}
              type={showPassword ? 'text' : 'password'}
              value={values.password}
              disableUnderline={true}
              placeholder="Contraseña"
              ref={passwordField}
              onChange={handleChange(PASSWORD)}
              onFocus={handleFocus}
              error={fieldsErrors.passwordError !== ''}
              endAdornment={
                <InputAdornment position="end">
                  <IconButton
                    aria-label="toggle password visibility"
                    onClick={handleClickShowPassword}
                    onMouseDown={handleMouseDownPassword}
                  >
                    {showPassword ? <Visibility /> : <VisibilityOff />}
                  </IconButton>
                </InputAdornment>
              }
            />
          </FormControl>
          {fieldsErrors.passwordError && <p style={styles.errorStyle}>{fieldsErrors.passwordError}</p>}

          <Button
            variant={submitVariant}
            className="mt-4 ml-auto"
            size="lg"
            type="submit"
            onClick={() => handleSubmit(dispatch, checkInputContent, values, fieldsErrors, clearFields)}
          >
            INICIAR SESIÓN
          </Button>
          <LinkBtn className="ml-auto mt-2" to="/recover_password">
            Recuperar contraseña
          </LinkBtn>
        </FormGroup>
      </Col>
    </Row>
  );
};

const handleSubmit = (dispatch, checkInputContent, values, fieldsErrors, clearFields) => {
  checkInputContent();
  if (fieldsErrors.loginError !== '' || fieldsErrors.passwordError !== '') {
    // alert('Hay errores en la página');
    return;
  }
  let { login } = values;
  if (login.indexOf('@') === -1) {
    login = login
      .replace(/\s/g, '')
      .replace(/\./g, '')
      .replace(/-/g, '');
  }
  dispatch(
    requestSignIn({
      user: {
        login,
        password: values.password
      }
    })
  );
};

const styles = {
  errorStyle: {
    display: 'flex',
    paddingLeft: 10,
    marginTop: -5,
    color: '#D33F49',
    fontSize: 12,
    alignItems: 'flex-start'
  }
};

在此处输入图像描述

编辑:我粘贴了整个代码)

但是,它不会清理输入

我在这里想念什么?

提前致谢

拉斐尔

4

0 回答 0