【问题标题】:How to handle errors in my form fields with a single function in ReactJS?如何使用 ReactJS 中的单个函数处理表单字段中的错误?
【发布时间】:2021-01-06 04:20:48
【问题描述】:

我有一个表单,用户需要回答 3 个问题才能注册新密码。所有字段均为必填项,在回答完 3 个问题之前,用户无法将数据发送到服务器。

我的问题是如何只用一个函数来处理输入字段错误?我目前为每个字段执行一个功能。这在性能水平上并不是很好。

例如,只需一个函数,我就可以获取在所有输入字段中输入的值:

const handleChangeField = (field) => (event) => {
  const value = event?.target?.value || "";
  setData((prev) => ({ ...prev, [field]: value }));
};

你能告诉我是否可以创建一个类似于上面的函数,但要处理错误?在这一刻,这就是我正在做的事情:

<TextField
  label="What is your mother's name?"
  className={classes.input}
  error={hasErrorMother}
  helperText={hasErrorMother ? "Required field*" : ""}
  value={data.motherName}
  onInput={(event) =>
    event.target.value.length > 0
      ? setHasErrorMother(false)
      : setHasErrorMother(true)
  }
  onChange={handleChangeField("motherName")}
/>

我处理onInput 中每个字段的错误。

这是我输入codesandbox的代码

非常感谢您。

【问题讨论】:

    标签: javascript reactjs react-material react-material-ui-form-validator


    【解决方案1】:

    这是一个想法:您继续使用handleChangeField,但进行一些修改以同时处理error。但首先,我们需要更改状态标题位:

    // Remove those
    // const [hasErrorMother, setHasErrorMother] = useState(false);
    // const [hasErrorBorn, setHhasErrorBorn] = useState(false);
    // const [hasErrorPet, setHasErrorPet] = useState(false);
    
    // Instead have the error state this way
    const [error, setError] = useState({
      motherName: false,
      birthplace: false,
      petName: false
    });
    
    ...
    // handleChangeField will have an extra line for error handling
    const handleChangeField = (field) => (event) => {
      const value = event?.target?.value || "";
      setData((prev) => ({ ...prev, [field]: value }));
      setError((prev) => ({ ...prev, [field]: value.length === 0 })); // THIS ONE
    };
    

    在 return 语句中,TextField 将变为:

    // onInput is removed, because onChange is taking care of the error
    <TextField
      label="What is your mother's name?"
      className={classes.input}
      error={error.motherName}
      helperText={error.motherName? "Required field*" : ""}
      value={data.motherName}
      onChange={handleChangeField("motherName")}
    />
    

    现在对于handleContinueAction,这也将更改如下:

    ...
    const handleContinueAction = () => {
      const isValid =
        data.motherName.length > 0 &&
        data.birthplace.length > 0 &&
        data.petName.length > 0;
    
      if (isValid) {
        console.log("Ok, All data is valid, I can send this to the server now");
      } else {
        // If you want to show error for the incomplete fields
        setError({
          motherName: data.motherName.length === 0,
          birthplace: data.birthplace.length === 0,
          petName: data.petName.length === 0
        })
      }
    };
    
    ...
    // and git rid of this part
    // const validateFields = (body) => {
    //   if (body.motherName.length === 0) {
    //     return setHasErrorMother(true);
    //   }
    
    //   if (body.birthplace.length === 0) {
    //     return setHhasErrorBorn(true);
    //   }
    
    //   if (body.petName.length === 0) {
    //     return setHasErrorPet(true);
    //   }
    
    //   return true;
    };
    

    【讨论】:

    • 嘿 Akram,谢谢你的帮助,我照你说的做了,但是当我按下按钮时,没有向用户显示任何错误,请查看我的代码框更新:codesandbox.io/s/handle-fields-erros-7o7mb?file=/src/Form/…
    • 当您按下按钮时,如果isValid 正确,它只会执行console.log。如果您想在 isValid 为 false 的情况下显示字段的错误消息,那么您可以添加一个 else 声明,类似于我刚刚在我编辑的答案中放入的声明
    • 完美!!!不是完美的!谢谢!!!
    • 乐于助人:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2020-10-28
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 2019-05-31
    • 2018-10-09
    相关资源
    最近更新 更多