reactjs react自动完成包上的useRef和type不起作用

7lrncoxx  于 2023-03-17  发布在  React
关注(0)|答案(1)|浏览(190)

我有点迷惑了,我在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>
    </>
  );
};
z9smfwbn

z9smfwbn1#

Typescript将inputRef的类型推断为MutableRefObject<undefined>。您必须指明引用将要使用的类型,并为引用分配初始值。

const inputRef = useRef<LegacyRef<Autocomplete> | undefined>(undefined);

相关问题