首页 > 解决方案 > react-bootstrap-typeahead TypeScript- Ref - getInstance does not exist

问题描述

Im using react-bootstrap-typeahead typescript, added types from @types/react-bootstrap-typeahead

In my typeahead from react functional component, I'm trying to access the typeahead ref and call the public methods of the component, as given here

import { Typeahead } from 'react-bootstrap-typeahead';

const typeahead = React.createRef();

<Typeahead
ref={(ref) => typeahead = ref}
id="basic-typeahead-single"
filterBy={['dialCode', 'name']}
inputProps={{
    className: 'attrib',
}}
labelKey={(option: any) => `${option.name}`}
onChange={(selected: any) => {
    console.log(selected);
}}
renderMenuItemChildren={(option) => (
    <div>
        <div>{option.name}   {option.section}</div>
    </div>
)}
options={employeeList}
selected={state.internationalization}>
</Typeahead>
<span className="arrow" onClick={() => {
    const instance = typeahead.getInstance();
    console.log("instance", instance);
    instance.clear();
    instance.focus();
}}><img src="/arrow.svg" /></span> 

It throws error - Property 'getInstance' does not exist on type 'RefObject'

so while creating ref I tried: const typeahead = React.createRef<Typeahead>(); But it seems something is missing for typescript

标签: reactjstypescriptreact-bootstrap-typeahead

解决方案


typeahead您从中创建的变量createRef是一个RefObject具有current引用您的组件的属性。

创建 ref 时,需要使用泛型指定组件类型。如您所见,Typeahead该类本身是泛型的,但泛型类型与您尝试执行的操作无关,因此您可以any说它是Typeahead具有任何类型数据的组件的引用。

const typeahead = React.createRef<Typeahead<any>>();

由于我们使用的是新createRef语法而不是旧的回调 refs,因此当您将 ref 传递给组件时,您只需传递整个 ref 对象。

<Typeahead ref={typeahead} ... />

要访问该实例,请查看.currentref 的属性,即nullTypeahead<any>

const instance = typeahead.current;

但是对于调用方法,你仍然会得到一个错误。无论出于何种原因,类中存在的这些公共方法都没有记录在类型定义中,因此打字稿不知道它们。

您可能希望与任何类型维护者一起提出这个问题,或者@types/react-bootstrap-typeahead自己编辑包,因为这似乎是一个疏忽。

但是您也可以使用自己的类型扩展类型。

declare module "react-bootstrap-typeahead" {
    interface Typeahead<T extends TypeaheadModel> extends React.Component<TypeaheadProps<T>> {
        clear(): void;
        focus(): void;
    }
}

在调用任何方法之前,您需要确保它typeahead不是。null最简洁的方法是使用可选链接?.

const instance = typeahead.current;
instance?.clear();
instance?.focus();

打字稿游乐场链接


推荐阅读