useRef "refers to a value, but is being used as a type here."

Ilj*_*lja 9 typescript reactjs react-hooks

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);
Run Code Online (Sandbox Code Playgroud)

AnimatedCircle is an SVG component from a third party library, and defining it this way causes error

在此处输入图片说明

Is there some universal way to define which element is ref?

小智 86

就我而言,我将文件重命名.ts.tsx. 再次重命名它修复了它。

  • 伙计,我所有的麻烦都是这个错误!坦克,你刚刚解决了我的情况,我花了 3 个小时在互联网上搜索有关此问题的信息。 (11认同)

Dan*_*try 11

AnimatedCircle是一个函数,而不是一个类型。这意味着它不能在TypeScript中代替类型使用,例如在的通用约束中useRef。相反,您需要使用将typeof operator转换为类型:

const circleRef = useRef<typeof AnimatedCircle | null>(null);
Run Code Online (Sandbox Code Playgroud)

  • 构造函数通常也是类型,不是吗? (2认同)

Muh*_*ooq 11

我遇到了同样的错误

ReactDOM.render(
<App store={store} persistor={persistor} basename={PUBLIC_URL} />,
document.getElementById("root");
Run Code Online (Sandbox Code Playgroud)

我将文件重命名为.tsx并解决了问题。原因是,当您使用React或 时ReactDOM,您必须将文件重命名.tsxts. 对于JavaScript.js有效但对于TypeScript.ts不起作用。