我正在使用react-bootstrap-typeahead,添加了来自@types/react-bootstrap-typeahead的类型
在我的来自react functional component的typeahead中,我尝试访问typeahead引用并调用组件的公共方法,就像给定的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“”
因此,在创建ref时,我尝试了:const typeahead = React.createRef<Typeahead>();,但似乎typescript缺少一些东西
发布于 2020-10-29 02:39:50
您从createRef创建的变量typeahead是一个具有引用您的组件的属性current的RefObject。
创建参照时,需要使用类属指定元件类型。正如您所看到的,Typeahead类本身是泛型的,但是泛型类型与您要做的事情无关,因此可以使用any来说明它是对包含任何类型数据的Typeahead组件的引用。
const typeahead = React.createRef<Typeahead<any>>();因为我们使用的是新的createRef语法,而不是旧的回调引用,所以当你将引用传递给组件时,你只是传递了整个引用对象。
<Typeahead ref={typeahead} ... />要访问该实例,可以查看ref的.current属性,该属性可以是null或Typeahead<any>。
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();https://stackoverflow.com/questions/64573358
复制相似问题