【发布时间】: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>
- 如何将值初始设置/重置为德国?
- 提交时如何发布国家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