reactjs - 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
解决方案
typeahead
您从中创建的变量createRef
是一个RefObject
具有current
引用您的组件的属性。
创建 ref 时,需要使用泛型指定组件类型。如您所见,Typeahead
该类本身是泛型的,但泛型类型与您尝试执行的操作无关,因此您可以any
说它是Typeahead
具有任何类型数据的组件的引用。
const typeahead = React.createRef<Typeahead<any>>();
由于我们使用的是新createRef
语法而不是旧的回调 refs,因此当您将 ref 传递给组件时,您只需传递整个 ref 对象。
<Typeahead ref={typeahead} ... />
要访问该实例,请查看.current
ref 的属性,即null
或Typeahead<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();
推荐阅读
- informatica-powercenter - 关于唯一序列的 Informatica 场景
- java - 使用 Citrus Admin UI 创建项目时出错
- c# - 尝试通过mvc中的Action方法返回视图和列表
- c - 如何从 C 主对角线上的二维数组中删除负元素
- javascript - 如何在 Angular 6 项目中添加引导程序?
- python - 无法将日期时间转换为纪元毫秒
- ansible - 如何在ansible playbook中比较两个不同主机的输出?
- java - setLayaut 没有回应礼节 Hgap
- compiler-errors - 无法在 rust include 中编译 CRC 库!(concat!(env!("OUT_DIR"), "/crc16_constants.rs"));
- javascript - 在 XMLHttpRequest 中请求 api 时出现错误