我有一个 countries
包含 id
的数组和 name
.目前我正在使用 Material UI Autocomplete
元素,我有一个 react 钩子(Hook)形式。当我提交表单时,我想获取国家 ID。目前它正在发布国家名称。有没有办法发布 id 而不是名称,而无需从名称中获取 id。
<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"
/>
)}
/>
最佳答案
使用 react-hook-form 的 Controller并将整个 Autocomplete
在 as
支柱。这样,当您提交表单时,您将获得所选选项的整个对象。
备注 : 在 react-hook-form 版本 6.x 中,onChange
is removed , as prop 会带一个函数,你可以得到onChange
作为参数。
Working demo - v6
<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,请参阅下面的演示和代码片段。Working demo - v5
<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 设置默认值。
代码片段:
useEffect(() => {
setTimeout(() => { // fake api
setValue(
"country",
{ label: "hi The Godfather", id: "1972" },
{ shouldDirty: true }
);
}, 2000);
}, []);
上面的演示 v6 已更新。另见 official demo of setValue usage here
关于reactjs - React Form Hook with Autocomplete Material UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62997374/