我正试图使用react hook表单制作一个包含两个字段的表单,其中文本字段的所需值取决于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>
isPickupPoint
标志正确更改,因为textfield
的disabled
道具工作正常。仅当选择PICKUP_POINT选项时,文本字段才处于活动状态。但所需的道具不起作用,它总是错误的。当我尝试在表单为空时提交表单时,会出现destinationType
错误标签,但当我尝试使用PICKUP_POINT选项和空的pickupPointId
字段提交表单时它不会出错。
我如何才能使这个动态所需的道具发挥作用?
根据这里的代码,isPickUpPoint
似乎按预期工作,因为它可以禁用。由于您对required使用了相同的属性,因此它应该流经。我怀疑这个错误可能存在于您的Controller
组件中。我会去那里看看,并确保该物业是你所期望的。
同样对于disabled,条件是!isPickUpPoint
,因此当它为false时,它将触发。
对于required,条件为isPickUpPoint
,因此它将在为true时触发。
这也有点脱节,因为它看起来是相同的输入。