在我正在开发的 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)