我们的目标是创建一个可重用的钩子来影响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扩展的任何类型,而不是any或assertion,请帮助。
dom不限于输入,它可以是div、input或span等,所以HTMLInputElement类型不适合这种情况。
发布于 2021-03-22 13:02:23
仔细查看错误消息:Type 'HTMLElement | null' is not assignable to type 'HTMLInputElement | null'.。根据消息,正确的类型是HTMLInputElement | null。此外,稍微更改一下useFocus也是有意义的:
useEffect(() => {
domRef.current?.focus()
}, [domRef]);https://stackoverflow.com/questions/66740303
复制相似问题