提问者:小点点

React Hook Form dynamic必需


我试图使用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>

因为TextFieldDisabled属性工作正常,所以IsPickupPoint标志会正确更改。 只有当选择了PICKUP_POINT选项时,文本字段才处于活动状态。 但是所需的道具不起作用,它总是假的。 当我尝试提交为空的表单时,destinationType错误标签会出现,但当我尝试提交带有PICKUP_POINT选项和空pickupPointID字段的表单时,它不会出现错误。

我如何才能使这个动态所需道具工作?


共1个答案

匿名用户

根据这里的代码,IsPickupPoint看起来像预期的那样工作,因为它适用于DISABLE。 由于您正在为required使用相同的属性,因此它应该通过。 我怀疑bug可能存在于您的controller组件中。 我会去看一看,确定这房子是你想要的。

对于禁用的情况,条件是!IsPickupPoint,因此当它为false时将触发。

对于required,条件是IsPickupPoint,因此当它为true时将触发。

这也是一个有点脱节,因为它看起来是相同的输入。