我使用 Material UI 的 Autocomplete 组件在 React 中制作了一个 Autocomplete 组件。这是代码
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. `
您能详细说明您正在通过什么
options
吗?
如果能提供codesandbox就更好了
这是因为您选择的
option
与value
中的
options
不匹配
“”值是自动完成的实际值。如果您想让它在空字段中工作,您可以:
// 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;
}}
由于 MUI 中进行了修复,这可能不再是问题,但我遇到了同样的问题,并且 Github 中的任何问题都不适用于我自己的场景。
我注意到,如果您最初传入 undefined 作为 value 属性,则自动完成组件会永久从不受控模式切换到受控模式(控制台日志实际上是这样说的!)。这意味着 value 属性随后由组件在内部处理,因此您无法从自动完成外部更改它。
解决方案是传入 NULL 作为值属性,而不是使组件保持不受控制模式,并且即使选项(或值)异步延迟,在刷新后传入的所有属性也会适当。