You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
To use useRef with TypeScript, it is actually pretty easy, all you need to do is provide the type that you want to the function via open and closed chevrons like you would with other React hooks:
How to use useRef with TypeScript
参考文章:
To use useRef with TypeScript, it is actually pretty easy, all you need to do is provide the type that you want to the function via open and closed chevrons like you would with other React hooks:
useRef()
定义如上,在使用时我们只需要在<>
处传入对应的泛型类型即可。useRef()
包裹变量包裹变量时,我们只需要保证泛型
T
与(初始值|存入值)类型匹配即可。useRef()
包裹Element
本例在
useRef<T>()
中传入了 typenull | HTMLParagraphElement
,指明当前useRef
可以是 typesnull
或HTMLParagraphElement
两者之一。HTMLParagraphElement
是因为我们最终存储的<p>
标签属于HTMLElement
元素类型,具体类型为HTMLParagraphElement
,可在vscode
中将鼠标悬浮到对应的标签元素上查看提示。null
类型,这是因为ref
对象不会直接初始化为<p>
标签,真正赋值为对应标签元素的时刻发生在第一次渲染render
完成后。假如不指定null
,程序将在编译阶段就报错。除了使用 联合类型 来避免初始化为
null
时导致的编译报错外,我们还可以使用!
非空断言,它的作用就是将null
和undefined
排除在检查范围之外。关于
MutableRefObject
MutableRefObject:
useRef
返回的ref
对象所对应的类型。一个空的 MutableRefObject 对应的类型接口
{ current: undefined }
,具体返回的类型由泛型T
指定。❗️**值得一提的是:**在使用
useRef()
时,尽量初始化null
值,尽管它默认会填写为undefined
,但大多数情况下,采用默认值会导致意外的错误。上述例子中,
useRef
若采用默认赋值undefined
会报错,因为html元素
的ref
对象不接受一个未定义的值作为其实例值。How to fix the “object is possibly ‘null’” error in useRef with TypeScript.
由于我们通常会设置
useRef
的初始值为null
,尽管有时候我们知道在运行的某个阶段ref.current
不可能取到null
值,但是程序仍会在编译阶段报错。解决方案一:
!
非空断言解决方案二:
?.
可选链操作符The text was updated successfully, but these errors were encountered: