目标是制作一个可重用的挂钩,影响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 | };
问题:我如何给出useRef<…的正确类型>((
正确的想法是给出从HTMLElememnt中导出的任何类型的类型,而不是任何或断言,请提供帮助。
dom不限于输入,它可以是div、input或span等,所以HTMLInputElement类型不适合这种情况。
仔细查看错误消息:Type 'HTMLElement | null' is not assignable to type 'HTMLInputElement | null'.
。根据消息,正确的类型是HTMLInputElement | null
。此外,将useFocus
更改一点是有意义的:
useEffect(() => {
domRef.current?.focus()
}, [domRef]);