【发布时间】:2020-08-21 09:52:05
【问题描述】:
useRef(null) 和 useRef(undefined)(或只是 useRef())有什么区别?
在 TypeScript 中,结果以不同的类型结束:
const undefinedRef: React.MutableRefObject<undefined> = useRef(undefined)
conse noArgRef: React.MutableRefObject<undefined> = useRef()
const nullRef: React.MutableRefObject<null> = useRef(null)
当将 ref 传递给另一个元素时,这也会产生进一步的后果:
const nullRef = useRef(null)
<div ref={nullRef} /> // this works
const undefinedRef = useRef()
<div ref={undefinedRef} /> // compiler failure!
/*
Type 'MutableRefObject<undefined>' is not assignable to type 'string | ((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement> | null | undefined'.
Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<HTMLDivElement>'.
Types of property 'current' are incompatible.
Type 'undefined' is not assignable to type 'HTMLDivElement | null'.ts(2322)
*/
尽管编译器失败,但它仍然适用于我的用例(使用来自 react-use 的 useClickAway 挂钩)
除了 TypeScript 类型之外,这有什么影响?
这是一个重现故障的 CodeSandbox:https://codesandbox.io/s/prod-resonance-j9yuu?file=/src/App.tsx
【问题讨论】:
标签: javascript reactjs typescript react-hooks