首页 > 解决方案 > 在发送表单之前调度 onBlur

问题描述

我有一个带有电子邮件的表单,它在后端创建一个帐户,用户可以在此步骤中更改电子邮件。这段代码通过将函数放在 onBlur 中来做到这一点,但是如果我更改输入中的电子邮件并且不离开该字段,则不会发生 onBlur。我可以直接点击提交,发送我的旧电子邮件以创建帐户。

这是代码:

const SendForm = ({ submit }) => {

  const onLabelSubmit = () => async (event, newValue, name) => {
      handleLabelSubmit(newValue, name);
  };

  const submitForm = () => {
    // validations 
    submit();
  };

  const handleSubmitAccount = (e) => {
    e.preventDefault();

    dispatch(submitAccount(field.name, field.email))
      .then(() => {
        submitForm();
      });
  };


  return (
      <form onSubmit={handleSubmitAccount}>
              <Field
                id="email"
                name="email"
                label="label"
                onBlur={onLabelSubmit(label.email)}
              />

            <Button type="submit">
              Submit Form
            </Button>
      </form>
  );
};

有什么办法可以做 onBlur 所做的事情,但是当我点击提交按钮时?我需要改善体验并避免错误。

谢谢!

标签: javascriptreactjsformsreact-redux

解决方案


使用 .向组件添加状态useState。它不会在您的输入字段中onBlur使用onChange和添加value属性,而是会在每个用户输入时触发,因此您将始终拥有最新的给定电子邮件和用户名。

const SendForm = ({ submit }) => {

  const [fields, setFields] = useState({ name: '', email: '' })

  const onFieldChange = () => async (newValue, name) => {
      setFields({ ...fields, [name]: newValue });
  };

  const submitForm = () => {
    // validations 
    submit();
  };

  const handleSubmitAccount = (e) => {
    e.preventDefault();

    dispatch(submitAccount(field.name, field.email))
      .then(() => {
        submitForm();
      });
  };


  return (
      <form onSubmit={handleSubmitAccount}>
              <Field
                id="email"
                name="email"
                label="label"
                value={fields.email}
                onChange={onFieldChange(label.email)}
              />

            <Button type="submit">
              Submit Form
            </Button>
      </form>
  );
};


推荐阅读