使用react-hook-form控制器 https://react-hook-form.com/v5/api/#Controller并把整个Autocomplete
in the as
支柱。这样,当您提交表单时,您将获得所选选项的整个对象。
Note:在react-hook-form版本6.x中,onChange
已移除 https://github.com/react-hook-form/documentation/pull/252, as 属性将采用一个函数,您可以获得onChange
作为参数。
工作演示 - v6 https://codesandbox.io/s/material-ui-react-hook-form-get-id-version-6-s4zvw?file=/demo.js
<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" }}
/>
Note:如果您使用的是 v5x,请参阅下面的演示和代码片段。
工作演示 - v5 https://codesandbox.io/s/material-ui-react-hook-form-get-id-q13c0?file=/demo.js
<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" }}
/>
Edit: 根据评论
您可以使用setValue https://react-hook-form.com/api/#setValue根据 api 设置默认值。
代码片段:
useEffect(() => {
setTimeout(() => { // fake api
setValue(
"country",
{ label: "hi The Godfather", id: "1972" },
{ shouldDirty: true }
);
}, 2000);
}, []);
上面的演示 v6 已更新。
另请参阅setValue 使用的官方演示在这里 https://codesandbox.io/s/react-hook-form-v6-setvalue-wjplb?file=/src/index.jsx