我有点迷惑了,我在autocomplete
组件的ref prop
上得到了以下错误。有人知道吗?我不明白为什么我不能在这个组件上使用react useRef?
No overload matches this call.
Overload 1 of 2, '(props: Props | Readonly<Props>): Autocomplete', gave the following error.
Type 'MutableRefObject<undefined>' is not assignable to type 'LegacyRef<Autocomplete> | undefined'.
Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<Autocomplete>'.
Types of property 'current' are incompatible.
Type 'undefined' is not assignable to type 'Autocomplete | null'.
Overload 2 of 2, '(props: Props, context: any): Autocomplete', gave the following error.
Type 'MutableRefObject<undefined>' is not assignable to type 'LegacyRef<Autocomplete> | undefined'.ts(2769)
代码:
const Search = () => {
const [searchValue, setSearchValue] = useState('');
const [isOpened, setIsOpened] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
const handleButtonOnClick = () => {
setSearchValue('');
setIsOpened(false);
inputRef.current.focus();
};
const handleOnSelect = (val: string, item: any) => {
setSearchValue(val);
setIsOpened(false);
console.info('test');
console.log(item);
};
const handleOnChange: React.ChangeEventHandler<HTMLInputElement> = (
e: React.ChangeEvent<HTMLInputElement>
) => {
setSearchValue(e.target.value);
setIsOpened(true);
};
return (
<>
<Autocomplete
getItemValue={item => item.description}
renderMenu={(items, value) => (
<div>{items.length === 0 ? `No matches for ${value}` : items}</div>
)}
shouldItemRender={(item, value) =>
item.description.toLowerCase().indexOf(value.toLowerCase()) > -1
}
items={data.Sheet}
renderItem={(item, isHighlighted) => (
<div style={{ background: isHighlighted ? 'lightgray' : 'white' }}>
{item.description}
</div>
)}
autoHighlight={false}
value={searchValue}
onChange={e => handleOnChange(e)}
onSelect={(val, item) => handleOnSelect(val, item)}
open={isOpened}
ref={inputRef}
/>
<Button value="clear" onClick={handleButtonOnClick}></Button>
</>
);
};
1条答案
按热度按时间z9smfwbn1#
Typescript将
inputRef
的类型推断为MutableRefObject<undefined>
。您必须指明引用将要使用的类型,并为引用分配初始值。