[英]React Material UI Autocomplete using React Hook Forms issue
我在使用 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>
在Bill建議的代碼框中,您可以看到一個確切的示例。
帶有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}
/>
因為所選國家實際上是 Object,所以您必須在defaultValues
中設置德國國家 object:
const { control, handleSubmit, register, reset } = useForm({
defaultValues: {
country: { name: 'Germany', id: 1234 },
}
});
如果您不想在defaultValues
Object 中“硬編碼”國家/地區,您可以將getCountries
調用上移一級並將其傳遞給表單。 您現在可以在所有數據可用時有條件地呈現表單,並在國家列表中找到國家,如下所示:
const MyForm = ({ countries }) => {
const { control, handleSubmit, register, reset } = useForm({
defaultValues: {
country: countries.find(({ name }) => name === 'Germany'),
}
});
這是最簡單的方法,它從反應鈎子中渲染 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.