首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React Hook Form dynamic required

React Hook Form dynamic required
EN

Stack Overflow用户
提问于 2020-07-25 22:51:49
回答 1查看 4.6K关注 0票数 7

我正在尝试使用react钩子表单创建一个包含两个字段的表单,其中文本字段的必需值取决于select下拉列表的值。

下面是我的代码:

代码语言:javascript
复制
  const { handleSubmit, control, errors } = useForm();

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

  const handleDestinationTypeChange: EventFunction = ([selected]) => {
    togglePickupPoint(selected.value === "PICKUP_POINT");
    return selected;
  };
代码语言:javascript
复制
            <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属性可以正常工作。仅当选择了PICKUP_POINT选项时,文本字段才处于活动状态。但是所需的属性不起作用,它总是错误的。当我尝试在表单为空的情况下提交表单时,出现destinationType错误标签,但是当我尝试提交带有PICKUP_POINT选项和空pickupPointId字段的表单时,它没有错误地通过。

我怎样才能让这个动态的必备道具工作呢?

EN

回答 1

Stack Overflow用户

发布于 2020-07-25 23:00:30

基于这里的代码,看起来isPickUpPoint可以像预期的那样工作,因为它可以在disable模式下工作。由于您对required使用了相同的属性,因此它应该流经。我怀疑bug可能存在于您的Controller组件中。我会在那里看一看,并确保该属性是您所期望的。

对于disabled,条件也是!isPickUpPoint,因此它将在为false时触发。

对于required,条件为isPickUpPoint,因此它将在为真时触发。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63089761

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档