【发布时间】:2021-01-24 22:43:13
【问题描述】:
通常当我使用 React + Typescript 并且我必须使用 refs 时,我通常会使用此检查:
const ref = useRef<HTMLDivElement>(null)
...
if(ref && ref.current)
但是最近,我收到了这个错误:
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)
关于这个错误意味着什么的任何想法?为了解决这个问题,作为一种变通方法,我添加了第三个检查:
if(ref && "current" in ref && ref.current)
但这看起来很糟糕,主要是当您必须同时处理多个引用时。
感谢您的帮助。
【问题讨论】:
-
引用是如何创建的?使用 useRef,您总是会得到一个 ref 对象,这就是您的普通代码可以工作的原因。但看起来这段代码可能会收到一个 ref 回调。
-
我正在创建这样的引用
const cardRef = useRef<HTMLDivElement>(null); -
这不应该产生您所描述的问题。您是否在某处重新定义了类型?比如
const ref: Ref<HtmlDivElement> = cardRef?或者将它作为道具传递给需要Ref<HtmlDivElement>的组件?
标签: javascript reactjs typescript