如何使用ReactJS中的单个函数处理表单字段中的错误?

问题描述

我有一个表格,用户需要回答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

中的代码

非常感谢您。

解决方法

这是一个主意:您继续使用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;
};

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...