【发布时间】:2020-11-15 06:36:29
【问题描述】:
我正在尝试使用反应挂钩表单制作一个包含两个字段的表单,其中文本字段的所需值取决于选择下拉列表的值。
这是我的代码:
const { handleSubmit, control, errors } = useForm();
const [isPickupPoint, togglePickupPoint] = useState(false);
const handleDestinationTypeChange: EventFunction = ([selected]) => {
togglePickupPoint(selected.value === "PICKUP_POINT");
return selected;
};
<Grid item xs={6}>
<InputLabel>Destination type</InputLabel>
<Controller
as={Select}
name="destinationType"
control={control}
options={[
{ label: "Pickup point", value: "PICKUP_POINT" },
{ label: "Shop", value: "SHOP" },
]}
rules={{ required: true }}
onChange={handleDestinationTypeChange}
/>
{errors.destinationType && (
<ErrorLabel>This field is required</ErrorLabel>
)}
</Grid>
<Grid item xs={6}>
<Controller
as={
<TextField
label="Pickup Point ID"
fullWidth={true}
disabled={!isPickupPoint}
/>
}
control={control}
name="pickupPointId"
rules={{ required: isPickupPoint }}
/>
{errors.pickupPointId && (
<ErrorLabel>This field is required</ErrorLabel>
)}
</Grid>
<Grid item xs={12}>
<Button
onClick={onSubmit}
variant={"contained"}
color={"primary"}
type="submit"
>
Save
</Button>
</Grid>
isPickupPoint 标志正确更改,因为 textfield 的 disabled 属性工作正常。只有选择选项选项选项时,文本字段就处于活动状态。但是所需的道具不起作用,它总是错误的。当我尝试在表单为空时提交表单时,会出现 destinationType 错误标签,但是当我尝试使用 PICKUP_POINT 选项提交表单并清空 pickupPointId 字段时,它会毫无错误地通过。
我怎样才能使这个动态所需的道具工作?
【问题讨论】:
标签: javascript reactjs react-hooks frontend react-hook-form