【发布时间】:2021-06-18 18:12:33
【问题描述】:
目标是制作一个影响 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不限于input,可以是div或者input或者span等,所以HTMLInputElement类型不适合这种情况。
【问题讨论】:
-
不是对象类型吗?
标签: javascript reactjs typescript react-hooks frontend