需要 React Hook Form 动态

Mat*_*att 6 javascript frontend reactjs react-hooks react-hook-form

我正在尝试使用 react hook form 制作一个包含两个字段的表单,其中文本字段的所需值取决于选择下拉列表的值。

这是我的代码:

  const { handleSubmit, control, errors } = useForm();

  const [isPickupPoint, togglePickupPoint] = useState(false);

  const handleDestinationTypeChange: EventFunction = ([selected]) => {
    togglePickupPoint(selected.value === "PICKUP_POINT");
    return selected;
  };

Run Code Online (Sandbox Code Playgroud)
            <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>
Run Code Online (Sandbox Code Playgroud)

isPickupPoint标志改变正确,因为disabled的道具textfield工作正常。只有在选择Pickup_Point选项时,文本字段就处于活动状态。但是所需的道具不起作用,它总是错误的。当我尝试在表单为空时提交表单时会destinationType出现错误标签,但是当我尝试使用 PICKUP_POINT 选项和空pickupPointId字段提交表单时,它通过没有错误。

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

小智 1

根据这里的代码,它看起来像isPickUpPoint预期的那样工作,因为它适用于禁用。由于您使用的是所需的相同属性,因此它应该流过。我怀疑该错误可能存在于您的Controller组件中。我会去那里看看,确保该房产符合您的预期。

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

对于必需的条件,isPickUpPoint因此当它为真时就会触发。

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