跳到主内容

react使用typescript引入第三方包报错,cannot be used as a JSX Component

· 2分钟阅读

问题

react 项目使用 typescript 开发,安装一个第三方组件 TimeAgo,启动项目后报错了,在 mac 跑项目没有问题,但是在 windows 上却报错了。

'TimeAgo' cannot be used as a JSX component.
Its instance type 'ReactTimeago<keyof IntrinsicElements | ComponentType<{}>>' is not a valid JSX element.
The types returned by 'render()' are incompatible between these types.
Type 'React.ReactNode' is not assignable to type 'import("/home/user/app/node_modules/@types/react-bootstrap-table-next/node_modules/@types/react/index").ReactNode'.
Type '{}' is not assignable to type 'ReactNode'.

原因

由于 @types/react-dom 包依赖于 @types/react,指定的版本是 '*',导致 @types/react 安装成最新的 release 版本(目前是18.x)。

解决

解决办法很简单,只需要指定 @types/react 版本即可。然而 npm 还未能指定依赖版本功能,我们使用 yarn 来处理

package.json 文件里面新加下面配置

{
"resolutions": {
"@types/react": "17.0.2",
"@types/react-dom": "17.0.2"
}
}

然后执行 yarn install ,重新 npm run start 即可。