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