如何解决如何使用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;
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。