typescript useRef“指的是一个值,但在此处被用作类型。”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/55576953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
useRef "refers to a value, but is being used as a type here."
提问by Ilja
I'm trying to figure out how to tell react which element is being used as ref i.e. in my case
我试图弄清楚如何告诉反应哪个元素被用作参考,即在我的情况下
const circleRef = useRef<AnimatedCircle>(undefined);
AnimatedCircle
is an SVG component from a third party library, and defining it this way causes error
AnimatedCircle
是来自第三方库的 SVG 组件,以这种方式定义它会导致错误
Is there some universal way to define which element is ref?
是否有一些通用的方法来定义哪个元素是 ref?
回答by Ishmeet Singh
In my case, I renamed the file as .ts
instead of .tsx
. Renaming it again fixed it.
就我而言,我将文件重命名.ts
为.tsx
. 再次重命名它修复了它。
回答by Dan Pantry
AnimatedCircle
is a function, not a type. This means it cannot be used in TypeScript in place of a type, like in the generic constraint of useRef
. Instead, you need to use the typeof operator
to convert to a type:
AnimatedCircle
是一个函数,而不是一个类型。这意味着它不能在 TypeScript 中代替类型使用,就像在useRef
. 相反,您需要使用typeof operator
来转换为类型:
const circleRef = useRef<typeof AnimatedCircle | null>(null);