我试图使用react hook form创建一个包含两个字段的表单,其中文本字段的所需值取决于select下拉列表的值。
下面是我的代码:
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>
因为TextField
的Disabled
属性工作正常,所以IsPickupPoint
标志会正确更改。 只有当选择了PICKUP_POINT选项时,文本字段才处于活动状态。 但是所需的道具不起作用,它总是假的。 当我尝试提交为空的表单时,destinationType
错误标签会出现,但当我尝试提交带有PICKUP_POINT选项和空pickupPointID
字段的表单时,它不会出现错误。
我如何才能使这个动态所需道具工作?
根据这里的代码,IsPickupPoint
看起来像预期的那样工作,因为它适用于DISABLE。 由于您正在为required使用相同的属性,因此它应该通过。 我怀疑bug可能存在于您的controller
组件中。 我会去看一看,确定这房子是你想要的。
对于禁用的情况,条件是!IsPickupPoint
,因此当它为false时将触发。
对于required,条件是IsPickupPoint
,因此当它为true时将触发。
这也是一个有点脱节,因为它看起来是相同的输入。