首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MUI自动完成不适用于react钩子形式。

MUI自动完成不适用于react钩子形式。
EN

Stack Overflow用户
提问于 2020-12-08 19:41:13
回答 2查看 1.1K关注 0票数 2

发行摘要

我在不同的时间会犯不同的错误。当我选择一个建议选项时,我会得到以下错误和警告:

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

另外,该选项没有被选中,并且输入变得没有定义。然而,当第二次尝试选择一个值时,它会被选中(但仍然会显示错误)。

当我清除输入时,我会得到以下错误:

代码语言:javascript
复制
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`.

自动完成组件代码

代码语言:javascript
复制
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

代码语言:javascript
复制
const districtOptions = [
    { value: "ciutatvella", label: "Ciutat Vella" },
    { value: "gracia", label: "Gràcia" },
    { value: "eixample", label: "L'Eixample" },
    { value: "sarria", label: "Sarrià" }
  ];

知道怎么回事吗?

EN

回答 2

Stack Overflow用户

发布于 2021-03-03 16:14:37

万一碰到这种情况:您必须使用自动完成的defaultValue,而不是控制器

票数 0
EN

Stack Overflow用户

发布于 2022-09-26 09:10:55

嘿,就用下面这个包吧:

https://www.npmjs.com/package/mui-react-hook-form-plus

代码语言:javascript
复制
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>
    )
}

见Demo

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65205791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档