【问题标题】:React Material UI Autocomplete using React Hook Forms issue使用 React Hook Forms 问题的 React Material UI Autocomplete
【发布时间】:2020-11-10 14:18:01
【问题描述】:

我在使用 Material UI 组件的 React Hook Forms 时遇到问题,我真的找不到这方面的资源。我有一个页面,我可以在其中获取国家和当前的个人资料信息,并且我想在表单中显示它。最初我想将国家设置为德国。

const [countries, setCountries] = useState([]);
const { control, handleSubmit, register, reset } = useForm();
const [currentProfile, setCurrentProfile] = useState<profiles.resProfileFields>();

useEffect(() => {
  const getProfileData = async () => {
    try {
      const profile = await api.get(profiles.getById, { id: profileId });
      if (profile != null && profile != undefined) {
        setCurrentProfile(profile);
        setcountryId(profile.country.id);
      }

    } catch (err) {
      console.log(`error getting: ${err}`);
    }
  };
  getProfileData();
  getCountries();
}, [profileId]);


useEffect(() => {
  reset(currentProfile);
}, [currentProfile]);

const getCountries = () => {
  api
    .get(routes.countries.list, {})
    .then(res => {
      setCountries(res);
    })
    .catch(err => { });
};

<form onSubmit={handleSubmit(onSubmit)}>


  <TextField
    inputRef={register}
    name="name"
    label="* Name"
    InputLabelProps={{
      shrink: true
    }}
    variant="outlined"
    placeholder="Name"
    className="form-item-full"
  />

  <Controller
    name="country"
    as={
      <Autocomplete
        className="form-item"
        options={countries}
        getOptionLabel={option => option.name}
        renderInput={params => (
          <TextField
            {...params}
            inputRef={register}
            label="Country"
            placeholder="Select a Country"
            InputLabelProps={{
              shrink: true
            }}
            variant="outlined"
          />
        )}
      />
    }
    defaultValue="Germany"
    control={control}
  />
</form>
  1. 如何将值初始设置/重置为德国?
  2. 提交时如何发布国家ID?

【问题讨论】:

  • 您能否提供一个工作示例和完整代码(组件定义和导入)?
  • 这是一个非常大的项目。我无法让 Material UI Autofill 与 React 挂钩表单一起使用。有什么我可以检查的例子吗?我想设置一个从 API 调用获得的初始值,然后我想提交和更新表单
  • 我还没用过react-hook-form,但是通过查看API文档你可以使用setValue method
  • 文档中有一个代码框可能会有所帮助:codesandbox.io/s/react-hook-form-v6-controller-qsd8r
  • @Christiaan 当我使用 setValue 时,我得到:一个组件正在将自动完成的不受控制的值状态更改为被控制。'

标签: javascript reactjs material-ui react-hook-form


【解决方案1】:

在比尔建议的codesandbox 中,您可以看到一个确切的示例。

带有Autocomplete 组件的Controller 应如下所示:

    <Controller
      render={props => (
        <Autocomplete
          {...props}
          options={countries}
          getOptionLabel={option => option.name}
          renderInput={params => (
            <TextField
              {...params}
              label="Country"
              placeholder="Select a Country"
              InputLabelProps={{
                shrink: true
              }}
              variant="outlined"
            />
          )}
          onChange={(_, data) => props.onChange(data)}
        />
      )}
      name="country"
      control={control}
    />

因为选择的国家实际上是一个对象,所以你必须在defaultValues中设置德国国家对象:

const { control, handleSubmit, register, reset } = useForm({ 
  defaultValues: {
    country: { name: 'Germany', id: 1234 },
  } 
});

如果您不想在defaultValues 对象中对国家/地区进行“硬编码”,您可以将getCountries 调用上移一级并将其传递给表单。您现在可以在所有数据可用时有条件地呈现表单,并在国家/地区列表中查找国家/地区,如下所示:

const MyForm = ({ countries }) => {
  const { control, handleSubmit, register, reset } = useForm({ 
    defaultValues: {
      country: countries.find(({ name }) => name === 'Germany'),
    } 
  });

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
  • 2020-06-10
  • 2020-09-06
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 2020-02-28
相关资源
最近更新 更多