发行摘要
我在不同的时间会犯不同的错误。当我选择一个建议选项时,我会得到以下错误和警告:
Material-UI: The getOptionLabel method of Autocomplete returned undefined instead of a string for 0
Material-UI: The value provided to Autocomplete is invalid. None of the options match with 0
另外,该选项没有被选中,并且输入变得没有定义。然而,当第二次尝试选择一个值时,它会被选中(但仍然会显示错误)。
当我清除输入时,我会得到以下错误:
A component is changing the controlled value state of Autocomplete to be uncontrolled.
Elements should not switch from uncontrolled to controlled (or vice versa).
Decide between using a controlled or uncontrolled Autocomplete element for the lifetime of the component.
The nature of the state is determined during the first render, it's considered controlled if the value is not `undefined`.自动完成组件代码
const AutocompleteUnit = ({control, label, name, ...rest}) => {
return (
<>
<Controller
onChange={([,data]) => data}
name={name}
as={
<Autocomplete
{...rest}
autoHighlight
style={{marginTop: "25px"}}
getOptionLabel={option => option.label}
renderInput={params => (
<TextField
{...params}
label={label}
variant="outlined"
/>
)}
/>
}
control={control}
defaultValue={rest.options[0]}
/>
</>
}Options
const districtOptions = [
{ value: "ciutatvella", label: "Ciutat Vella" },
{ value: "gracia", label: "Gràcia" },
{ value: "eixample", label: "L'Eixample" },
{ value: "sarria", label: "Sarrià" }
];知道怎么回事吗?
发布于 2021-03-03 16:14:37
万一碰到这种情况:您必须使用自动完成的defaultValue,而不是控制器
发布于 2022-09-26 09:10:55
嘿,就用下面这个包吧:
https://www.npmjs.com/package/mui-react-hook-form-plus
import { HookAutoComplete, useHookForm } from 'mui-react-hook-form-plus ';
const Component = () => {
const {registerState, handleSubmit} = useHookForm({
defaultValues: { movie: '' },
});
const onSubmit = (data: typeof defaultValues) => {
// will run if it is valid
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
<HookAutoComplete
{...registerState('movie')}
autocompleteProps={{
options: ['Fight Club', 'Top Gun', 'Titanic']
}}
textFieldProps={{
label: 'Movie',
placeholder: 'search...',
}}
/>
<button type='submit'>Submit</button>
</form>
)
}https://stackoverflow.com/questions/65205791
复制相似问题