问题描述
我有一个表格,用户需要回答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;
};