在我正在开发的 React 代码库中,我有一个自定义钩子,它接受 RefObject 作为参数,以及与此类钩子一起使用的随附提供程序:
export const ScrollUtilsProvider = React.forwardRef<HTMLDivElement, ScrollUtilsProviderProps>(
(props, ref) => {
const scrollUtils = useScrollUtils(ref) // issue happens on this line
return <div ref={ref}><ScrollUtilsContext.Provider value={scrollUtils}>{props.children}</ScrollUtilsContext.Provider></div>
},
)
export const useScrollUtils = <T extends Element>(ref: RefObject<T>) => {
return {
// some cool functions w/ the passed ref
}
}
Run Code Online (Sandbox Code Playgroud)
我收到的错误消息:
Argument of type 'ForwardedRef<HTMLDivElement>' is not assignable to parameter of type 'RefObject<HTMLDivElement>'.
Type 'null' is not assignable to type 'RefObject<HTMLDivElement>'.
Run Code Online (Sandbox Code Playgroud)
深入研究这两种类型,我意识到它们确实不同:
Argument of type 'ForwardedRef<HTMLDivElement>' is …Run Code Online (Sandbox Code Playgroud) 通常,当我使用 React + Typescript 并且必须使用 refs 时,我通常使用此检查:
const ref = useRef<HTMLDivElement>(null)
...
if(ref && ref.current)
Run Code Online (Sandbox Code Playgroud)
但最近,我收到此错误:
Property 'current' does not exist on type '((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement>'.
Property 'current' does not exist on type '(instance: HTMLDivElement | null) => void'.ts(2339)
Run Code Online (Sandbox Code Playgroud)
关于这个错误意味着什么的任何想法?为了解决这个问题,作为一种解决方法,我添加了第三个检查:
if(ref && "current" in ref && ref.current)
Run Code Online (Sandbox Code Playgroud)
但这看起来很糟糕,主要是当您必须同时处理多个引用时。
谢谢你的帮助。