我正在尝试使用react钩子表单创建一个包含两个字段的表单,其中文本字段的必需值取决于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字段的表单时,它没有错误地通过。
我怎样才能让这个动态的必备道具工作呢?
发布于 2020-07-25 23:00:30
基于这里的代码,看起来isPickUpPoint可以像预期的那样工作,因为它可以在disable模式下工作。由于您对required使用了相同的属性,因此它应该流经。我怀疑bug可能存在于您的Controller组件中。我会在那里看一看,并确保该属性是您所期望的。
对于disabled,条件也是!isPickUpPoint,因此它将在为false时触发。
对于required,条件为isPickUpPoint,因此它将在为真时触发。
这也有点脱节,因为它看起来是相同的输入。
https://stackoverflow.com/questions/63089761
复制相似问题