【问题标题】:react-bootstrap-typeahead TypeScript- Ref - getInstance does not existreact-bootstrap-typeahead TypeScript- Ref - getInstance 不存在
【发布时间】:2020-10-28 12:58:37
【问题描述】:

我使用 react-bootstrap-typeahead 打字稿,从@types/react-bootstrap-typeahead添加类型

在我的 react 功能组件的 typeahead 中,我试图访问 typeahead ref 并调用组件的公共方法,如给定的here

从 'react-bootstrap-typeahead' 导入 { 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> 

它引发错误 - 类型“RefObject”上不存在属性“getInstance”

所以在创建参考时我尝试过:const typeahead = React.createRef&lt;Typeahead&gt;(); 但是打字稿似乎缺少一些东西

【问题讨论】:

    标签: reactjs typescript react-bootstrap-typeahead


    【解决方案1】:

    您从createRef 创建的变量typeahead 是一个RefObject,其属性current 引用了您的组件。

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

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

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

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

    要访问实例,请查看引用的.current 属性,即nullTypeahead&lt;any&gt;

    const instance = typeahead.current;
    

    但是调用方法还是会报错。无论出于何种原因,exist on the class 的这些公共方法都没有记录在 in the type definitions 中,因此 typescript 不知道它们。

    您可能想与任何类型维护者一起提出这个问题,或者自己编辑 @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();
    

    Typescript Playground Link

    【讨论】:

    • 在模块中扩展接口的解决方案不适用于AsyncTypeahead。有人可以提出解决方案吗?
    猜你喜欢
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多