[英]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.