Material UI 自动完成功能不更新输入值(React)

发布于 2025-01-20 04:08:31 字数 1756 浏览 3 评论 0原文

我使用材料UI的自动完成组件在React中制作了一个自动完成组件。这是我输入时选项显示的代码

import { useState } from "react";
import { Autocomplete as MuiAutcomplete } from "@mui/material";
import {useFormContext} from "react-hook-form";


interface props {
    name: string,
    options?: string[],
    getOptions?: (value: string) => {
        label: string,
        id: number
    }[] | string[],
    freeSolo?: boolean
};

const Autocomplete = ({name, options=[], getOptions, freeSolo=false}: props) => {
    const [autocompleteValues, setAutocompleteValues] = useState<any[]>(options);
    const {setValue, getValues} = useFormContext();

    return (
        <MuiAutcomplete
            options={autocompleteValues}
            renderInput={({ InputProps, inputProps }) => (
                <div ref={InputProps.ref}>
                <input
                    type="text"
                    {...inputProps}
                    className="bg-transparent outline-none p-1"
                />
                </div>
            )}
            value={getValues(name)}
            onChange={(e, v) => {
                setValue(name, v);
            }}
            getOptionLabel={(option) => option.label || option}
            freeSolo={freeSolo}
        />
    )
}

export default Autocomplete;

,但是当实际选择一个选项时,输入字段实际上并未更新。相反,它显示了此错误:

`MUI: The value provided to Autocomplete is invalid.None of the options match with `""`.You can use the `isOptionEqualToValue` prop to customize the equality test. `

我不完全确定发生了什么。这是一个视频,显示错误,以防您需要澄清 https://i.sstatic.net/qmfog.jpg (对不起,较低的Res,Imgur的压缩破坏了)

I made an Autocomplete component in React using Material UI's Autocomplete component. Here's the code

import { useState } from "react";
import { Autocomplete as MuiAutcomplete } from "@mui/material";
import {useFormContext} from "react-hook-form";


interface props {
    name: string,
    options?: string[],
    getOptions?: (value: string) => {
        label: string,
        id: number
    }[] | string[],
    freeSolo?: boolean
};

const Autocomplete = ({name, options=[], getOptions, freeSolo=false}: props) => {
    const [autocompleteValues, setAutocompleteValues] = useState<any[]>(options);
    const {setValue, getValues} = useFormContext();

    return (
        <MuiAutcomplete
            options={autocompleteValues}
            renderInput={({ InputProps, inputProps }) => (
                <div ref={InputProps.ref}>
                <input
                    type="text"
                    {...inputProps}
                    className="bg-transparent outline-none p-1"
                />
                </div>
            )}
            value={getValues(name)}
            onChange={(e, v) => {
                setValue(name, v);
            }}
            getOptionLabel={(option) => option.label || option}
            freeSolo={freeSolo}
        />
    )
}

export default Autocomplete;

The options display just fine when I type but when actually selecting an option the input field doesn't actually get updated. It instead shows this error:

`MUI: The value provided to Autocomplete is invalid.None of the options match with `""`.You can use the `isOptionEqualToValue` prop to customize the equality test. `

I'm not entirely sure what's going on. Here's a video showing the error in case you need clarification https://i.sstatic.net/QmfoU.jpg (sorry for low res, Imgur's compression ruined it)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

彼岸花似海 2025-01-27 04:08:32

您能否请详细信息选项您正在通过吗?

如果您可以提供代码框,那就更好了。

您要选择的option不匹配value in options

Can you please details about what options are you passing?

It will be better if you can provide a codesandbox.

It is due to the option which you are selecting is not matching the value in options

葮薆情 2025-01-27 04:08:32

“”值是自动完成的实际值。如果您想在空地上使用它,则可以:

// Set value to null. If you set it to 'undefined' it will give you a warning similar to the current one
value={getValues(name) || null}

// Override the function which checks if the value is equal to the option.
// Basically, you handle the empty string here.
isOptionEqualToValue={(option, currentValue) => {
            if (currentValue === '') return true;
            return option.name === currentValue.name;
          }}

The "" value is an actual value for auto complete. If you want to make it work with an empty field you can:

// Set value to null. If you set it to 'undefined' it will give you a warning similar to the current one
value={getValues(name) || null}

Or

// Override the function which checks if the value is equal to the option.
// Basically, you handle the empty string here.
isOptionEqualToValue={(option, currentValue) => {
            if (currentValue === '') return true;
            return option.name === currentValue.name;
          }}
清旖 2025-01-27 04:08:32

由于MUI中的修复程序,这可能不再是一个问题,但是我遇到了同样的问题,而GitHub问题中没有任何应用于我自己的情况。

我注意到,如果您通过不确定的值作为值支柱最初将自动完成组件从不受控制的模式永久切换到控制模式(控制台日志实际上是这样说的!)。这意味着然后由组件内部对价值道具进行处理,因此您无法从外部自动完成。

该解决方案是通过null传递,因为价值支柱将组件保持不受控制的模式,并且在此之后通过适当的刷新后传递的所有道具即使选项(或值)延迟了异步。

This may no longer be a problem due to fixes made in MUI but I was having the same issue and nothing in the Github issues applied to my own scenario.

I noticed that if you pass in undefined as the value prop initially the Autocomplete component switches from Uncontrolled to Controlled mode permanently (the console logs actually say this!). This means that the value prop is then handled internally by the component so you cannot change it from outside Autocomplete.

The solution was to pass in NULL as the value prop instead which keeps the component in Uncontrolled mode and all props passed in after that refresh appropriately even if the options (or value) are ASYNC delayed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文