使用React Hook Forms问题进行React Material UI自动完成

时间:2020-07-21 08:28:36

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

我在使用Material UI组件的React Hook表单上遇到问题,我真的找不到相关的资源。我有一个页面,可在其中获取国家/地区和当前的个人资料信息,并希望在表单内显示它。最初,我想将国家/地区设置为德国。

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?

1 个答案:

答案 0 :(得分:5)

在Bill建议的codesandbox中,您可以看到一个确切的例子。

带有MERGE INTO T2 XX USING (select previous_last_name, SYS_GUID() as cluster_id from T2) S ON (XX.last_name = S.previous_last_name) WHEN MATCHED THEN UPDATE SET XX.group_id = S.cluster_id; MERGE INTO T2 XX USING (select last_name, group_id as cluster_id from T2) S ON (XX.previous_last_name = S.last_name) WHEN MATCHED THEN UPDATE SET XX.group_id = S.cluster_id; 组件的Controller应该看起来像这样:

Autocomplete

由于所选国家实际上是一个对象,因此您必须在 <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