[英]react-bootstrap-typeahead TypeScript- Ref - getInstance does not exist
我使用 react-bootstrap-typeahead 打字稿,从@types/react-bootstrap-typeahead
添加类型
在从反应的官能组件我预输入,我试图访问预输入ref和调用组件的公共方法,给这里
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>
它引发错误 - 类型“RefObject”上不存在属性“getInstance”
所以在创建 ref 我试过: const typeahead = React.createRef<Typeahead>();
但是打字稿似乎缺少一些东西
可变typeahead
您从创建createRef
是RefObject
与属性current
引用您的组件。
创建 ref 时,需要使用泛型指定组件类型。 如您所见, Typeahead
类本身是泛型的,但泛型类型与您要执行的操作无关,因此您可以使用any
表示它是对具有任何类型数据的Typeahead
组件的引用。
const typeahead = React.createRef<Typeahead<any>>();
由于我们使用新的createRef
语法而不是旧的回调 refs,因此当您将 ref 传递给组件时,您只需传递整个 ref 对象。
<Typeahead ref={typeahead} ... />
要访问该实例,请查看 ref 的.current
属性,该属性为null
或Typeahead<any>
。
const instance = typeahead.current;
但至于调用方法,你仍然会得到一个错误。 无论出于何种原因, 存在于类中的这些公共方法未记录在类型定义中,因此 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.