【发布时间】:2021-06-29 20:45:51
【问题描述】:
我有一个自定义钩子,它在我的 TS 应用程序中返回值 useRef。不幸的是,它抱怨我返回的 ref 的类型,我不知道如何正确输入。
这就是我的钩子的样子:
interface MyHookInterface {
someBooleanState: boolean
myRef: HTMLElement | null
}
const useMyHook = (): MyHookInterface => {
const [someBooleanState, setSomeBooleanState] = useState<boolean>(false)
const myRef = useRef<HTMLElement | null>(null)
useEffect(() => {
const el = myRef.current // what type should this be?
// Complaining that el possibly undefined
if(el?.offsetWidth < el?.scrollWidth){
// do stuff
}
}, [])
return {
someBooleanState,
myRef, // Getting: Type 'MutableRefObject<HTMLElement | null>' is missing the following properties from type 'HTMLElement': accessKey, accessKeyLabel, autocapitalize, dir, and 234 more
}
}
正如您在 cmets 中看到的,我的钩子有一些与打字有关的错误:
1- 不知道如何在界面中输入myRef。请记住,它是用于多种类型的 HTML 元素,所以我不能在这里指定它是 div 还是什么。
2- 不知道如何输入el,但对其属性的访问抱怨它是undefined
如何在我的钩子中正确键入这些值?
【问题讨论】:
-
在您的界面中,您将
myRef的返回类型指定为 HTMLELement,但在useMyHook中您将返回 Ref 对象。你应该返回{ myRef: myRef.current }
标签: reactjs typescript react-hooks use-ref