[英]React Material UI Autocomplete using React Hook Forms issue
I am having issues with React Hook Forms with Material UI Components and I can't really find resources on this.我在使用 Material UI 组件的 React Hook Forms 时遇到问题,我真的找不到这方面的资源。 I have a page where I fetch the countries and the current profile information and I want to show it inside the form.
我有一个页面,我可以在其中获取国家和当前的个人资料信息,并且我想在表单中显示它。 Initially I want to set the country to Germany.
最初我想将国家设置为德国。
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>
In the codesandbox suggested by Bill you can see an exact example.在Bill建议的代码框中,您可以看到一个确切的示例。
The Controller
with the Autocomplete
component should look like this:带有
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}
/>
Because the selected country actually is an Object, you will have to set the German country object in the defaultValues
:因为所选国家实际上是 Object,所以您必须在
defaultValues
中设置德国国家 object:
const { control, handleSubmit, register, reset } = useForm({
defaultValues: {
country: { name: 'Germany', id: 1234 },
}
});
If you don't want to 'hardcode' the country in the defaultValues
Object, you could move the getCountries
call up one level and pass it to the form.如果您不想在
defaultValues
Object 中“硬编码”国家/地区,您可以将getCountries
调用上移一级并将其传递给表单。 You can now conditionally render the form when all data is available and find the country in the countries list like so:您现在可以在所有数据可用时有条件地呈现表单,并在国家列表中找到国家,如下所示:
const MyForm = ({ countries }) => {
const { control, handleSubmit, register, reset } = useForm({
defaultValues: {
country: countries.find(({ name }) => name === 'Germany'),
}
});
Here is the simplest way to do it render your Autocomplete
component inside Controller from react hook from, use onChange
and value
from the render
function to control the value这是最简单的方法,它从反应钩子中渲染 Controller 中的
Autocomplete
组件,使用render
function 中的onChange
和value
来控制值
<Controller
control={control}
name="type"
rules={{
required: 'Veuillez choisir une réponse',
}}
render={({ field: { onChange, value } }) => (
<Autocomplete
freeSolo
options={['field', 'select', 'multiple', 'date']}
onChange={(event, values) => onChange(values)}
value={value}
renderInput={(params) => (
<TextField
{...params}
label="type"
variant="outlined"
onChange={onChange}
/>
)}
/>
)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.