【问题标题】:React Hook Form dynamic required需要 React Hook Form 动态
【发布时间】: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 标志正确更改,因为 textfielddisabled 属性工作正常。只有选择选项选项选项时,文本字段就处于活动状态。但是所需的道具不起作用,它总是错误的。当我尝试在表单为空时提交表单时,会出现 destinationType 错误标签,但是当我尝试使用 PICKUP_POINT 选项提交表单并清空 pickupPointId 字段时,它会毫无错误地通过。

我怎样才能使这个动态所需的道具工作?

【问题讨论】:

    标签: javascript reactjs react-hooks frontend react-hook-form


    【解决方案1】:

    根据此处的代码,isPickUpPoint 似乎按预期工作,因为它适用于禁用。由于您对 required 使用相同的属性,因此它应该流过。我怀疑该错误可能存在于您的 Controller 组件中。我会去那里看看,并确保该属性是您所期望的。

    同样对于禁用条件是!isPickUpPoint,所以它会在它为假时触发。

    如果需要,条件是isPickUpPoint,所以它会在它为真时触发。

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

    【讨论】:

    • Controller 组件实际上是一个 react-hooks-form 组件,所以恐怕我能做的不多。除非有什么我没看到?
    • 嗯,disabled 和 required 之间的不匹配怎么办?这是故意的吗?
    • 是的,如果选择了 PICKUP_POINT 选项,则应启用该字段(因此 !isPickupPoint - 如果未选择 PICKUP_POINT 则应禁用该字段)。并且当该字段启用时,它应该是必需的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 2022-01-06
    • 2021-07-16
    • 2020-09-24
    • 1970-01-01
    相关资源
    最近更新 更多