【问题标题】:Why required check not working after removing element?为什么删除元素后所需的检查不起作用?
【发布时间】:2020-02-10 00:11:03
【问题描述】:

您能否告诉我为什么我需要的检查在自动完成中不起作用。我正在使用带有反应钩子形式的material UI。 重现步骤

  • 单击Submit 按钮,显示字段为必填项。
  • 然后从列表中选择任何元素。
  • 删除选中的元素然后再次点击提交按钮。它应该 显示“必填”字段检查。但它没有显示任何内容,为什么??

这是我的代码 https://codesandbox.io/s/mui-autocomplete-with-react-hook-form-0wvpq

 <Controller
      as={
        <Autocomplete
          id="country-select-demo"
          multiple
          style={{ width: 300 }}
          options={countries}
          classes={{
            option: classes.option
          }}
          autoHighlight
          getOptionLabel={option => option.label}
          renderOption={(option, { selected }) => (
            <React.Fragment>
              <Checkbox
                icon={icon}
                checkedIcon={checkedIcon}
                style={{ marginRight: 8 }}
                checked={selected}
              />
              {option.label} ({option.code}) +{option.phone}
            </React.Fragment>
          )}
          renderInput={params => (
            <TextField
              {...params}
              label="Choose a country"
              variant="outlined"
              fullWidth
              name="country"
              inputRef={register({ required: true })}
              //  required
              error={errors["country"] ? true : false}
              inputProps={{
                ...params.inputProps,
                autoComplete: "disabled" // disable autocomplete and autofill
              }}
            />
          )}
        />
      }
      onChange={([event, data]) => {
        return data;
      }}
      name="country"
      control={control}
    />

【问题讨论】:

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


    【解决方案1】:

    最初加载表单时,表单的值是一个空对象 -

    {}
    

    当您选择一个国家/地区(例如“安道尔”)时,表单的值变为:

    {"country":[{"code":"AD","label":"Andorra","phone":"376"}]}
    

    然后当您取消选择国家/地区时,表单的值变为:

    {"country":[]}
    

    从技术上讲,空数组符合“必需”标准(毕竟它不为 null),因此不会触发所需的处理程序。

    您可以通过在 App 类中显示表单的值来验证这种情况 -

    const { control, handleSubmit, errors, register, getValues } = useForm({});
    return (
      <form noValidate onSubmit={handleSubmit(data => console.log(data))}>
        <Countries control={control} errors={errors} register={register} />
        <Button variant="contained" color="primary" type="submit">
          Submit
        </Button>
        <code>{JSON.stringify(getValues())}</code>
      </form>
    );
    

    简单的解决方法是不要从您的控件返回一个空数组作为值 - 如下更新您的 onChange 处理程序 -

    onChange={([event, data]) => {
        return data && data.length ? data : undefined;
    }}
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 2021-03-31
    相关资源
    最近更新 更多