![](/img/trans.png)
[英]How to use useRef hook and getClientBoundingRect with React and Typescript?
[英]typescript - Question about React typescript useRef
目標是制作一個影響 DOM 的可重用鈎子。
import { useEffect, useRef } from 'react';
function useFocus() {
const domRef = useRef<HTMLElement | null>(null);
useEffect(() => {
domRef.current?.focus()
}, []);
return {
domRef
};
}
const App = () => {
const { domRef } = useFocus();
return (
<div>
<input type='text' ref={domRef} />
</div>
);
};
export default App;
TypeScript error in /Users/yoki/Code/Demos/use-ref-demo/src/App.tsx(20,26):
Type 'MutableRefObject<HTMLElement | null>' is not assignable to type 'LegacyRef<HTMLInputElement> | undefined'.
Type 'MutableRefObject<HTMLElement | null>' is not assignable to type 'RefObject<HTMLInputElement>'.
Types of property 'current' are incompatible.
Type 'HTMLElement | null' is not assignable to type 'HTMLInputElement | null'.
Type 'HTMLElement' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 49 more. TS2322
18 | return (
19 | <div>
> 20 | <input type='text' ref={domRef} />
| ^
21 | </div>
22 | );
23 | };
正確的想法是給出從 HTMLElememnt 擴展的任何類型的類型,而不是任何或斷言,請幫助。
dom 不限於 input,它可以是 div 或 input 或 span 等,因此 HTMLInputElement 類型不適合這種情況。
仔細查看錯誤消息: Type 'HTMLElement | null' is not assignable to type 'HTMLInputElement | null'.
Type 'HTMLElement | null' is not assignable to type 'HTMLInputElement | null'.
. 正確的類型,根據消息是HTMLInputElement | null
HTMLInputElement | null
。 此外,稍微改變useFocus
是有意義的:
useEffect(() => {
domRef.current?.focus()
}, [domRef]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.