我有一个用Formik编写的表单。我想在没有选择类别时禁用子类别。子类目应该只在类别被选中时打开,否则它将被禁止被用户选择。请告诉我如何才能做到这一点。先谢谢你了。请看下面的示例代码。
const categoriesList = uniqueCategory.map((option) => ({
label: option.category,
}));
const subcategoriesList = uniqueSubCategory.map((option) => ({
label: option.sub_category,
}));
return (
<div className='container'>
<Formik
validateOnChange={true}
// form fields
initialValues={{
category: "",
sub_category: "",
}}
validationSchema={validationSchema}
onSubmit={(data, { setSubmitting, resetForm }) => {
setSubmitting(true);
try {
const body = {
category: selectedCategories.label,
sub_category: selectedSubCategories.label,
};
console.log(body);
const response = fetch(
"http://" + hosted + ":5000/createpart",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body),
}
)
.then((response) => {
// response.json();
})
.then(() => {
setSubmitting(false);
resetForm();
})
.then(() => {
console.log("Success");
setOpen(true);
})
.catch((error) => {
console.error("Error:", error);
alert("Failed to submit... ");
});
} catch (err) {
console.error(err.message);
}
}}
>
{({
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit,
isSubmitting,
}) => (
<div className='container'>
<Snackbar open={open} setOpen={setOpen} />
<Form onSubmit={handleSubmit}>
<Row style={formStyle}>
<Col md={6}>
<VirtSelect
placeholder='Category'
name='category'
styles={reactSelectStyles998}
options={categoriesList}
value={selectedCategories}
onChange={handleChangeSelectCategories}
/>
</Col>
<Col md={6}>
<VirtSelect
placeholder='Sub-Category'
name='sub_category'
styles={reactSelectStyles998}
options={subcategoriesList}
value={selectedSubCategories}
onChange={handleChangeSelectSubCategories}
/>
</Col>
</Row>
</Form>
</div>
)}
</Formik>
</div>
);
};
在呈现子类目之前加一个条件检查即可。
values.category && (
<Col md={6}><VirtSelect placeholder='Sub-Category' name='sub_category' styles={reactSelectStyles998} options={subcategoriesList} value={selectedSubCategories} onChange={handleChangeSelectSubCategories}/></Col>)