使用自动完成材料UI响应表单挂钩 [英] React Form Hook with Autocomplete Material UI
问题描述
我有一个 country
数组,其中包含 id
和 name
.目前,我正在使用Material UI Autocomplete
元素,并且具有react hook表单.提交表单时,我想获取国家/地区ID.目前,它正在发布国家/地区名称.有没有一种方法可以发布ID而不是名称,而无需从名称中获取ID.
I have a countries
array which contains id
and name
. Currently I am using a Material UI Autocomplete
element and I have a react hook form. When I submit the form, I want to fetch the country Id. Currently it is posting the country name. Is there a way to post the ids instead of the names without going and fetching the id from the name.
<Autocomplete
className="form-item"
options={countries}
getOptionLabel={option => option.name}
renderInput={params => (
<TextField
{...params}
inputRef={register}
label="Country"
name="country"
placeholder="Select a Country"
InputLabelProps={{
shrink: true
}}
variant="outlined"
/>
)}
/>
推荐答案
Use react-hook-form's Controller and put the entire Autocomplete
in the as
prop. With this, when you submit the form you will get the entire object of the selected option.
注意:在react-hook-form版本6.x中, onChange
Note: In react-hook-form version 6.x, the onChange
is removed, the as prop will take a function and you can obtain onChange
as param.
<Controller
as={({ onChange }) => (
<Autocomplete
className="form-item"
options={countries}
onChange={(_, data) => onChange(data)}
getOptionLabel={option => option.label}
renderInput={params => (
<TextField
{...params}
label="Country"
placeholder="Select a Country"
InputLabelProps={{
shrink: true
}}
variant="outlined"
/>
)}
/>
)}
name="country"
control={control}
defaultValue={{ label: "The Shawshank Redemption", id: "1994" }}
/>
注意:如果您使用的是v5x,请参见下面的演示和代码段.
Note: If you are using v5x then see demo and code snippet below.
<Controller
as={
<Autocomplete
className="form-item"
options={countries}
getOptionLabel={option => option.label}
renderInput={params => (
<TextField
{...params}
label="Country"
placeholder="Select a Country"
InputLabelProps={{
shrink: true
}}
variant="outlined"
/>
)}
/>
}
name="country"
control={control}
onChange={([, data]) => data}
defaultValue={{ label: "The Shawshank Redemption", id: "1994" }}
/>
修改:基于评论您可以使用 setValue 来基于api设置默认值.
Edit: based on comment You can use setValue to set default values based on an api.
代码段:
useEffect(() => {
setTimeout(() => { // fake api
setValue(
"country",
{ label: "hi The Godfather", id: "1972" },
{ shouldDirty: true }
);
}, 2000);
}, []);
上面的演示v6已更新.
Demo v6 above is updated.
这篇关于使用自动完成材料UI响应表单挂钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!