TS2786'组件'不能用作JSX组件

发布于 2025-01-20 13:32:45 字数 942 浏览 4 评论 0 原文

我有一个不编译的TypeScript应用程序。许多组件具有渲染方法,该方法键入返回 React.ReactNode react.reeactelement 。在编译中,报告了许多与以下情况相似的错误:

TS2786: 'MessagesWidget' cannot be used as a JSX component.
 Its instance type 'MessagesWidget' 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/node/app/node_modules/@types/react-calendar/node_modules/@types/react/index").ReactNode'.

为什么编译器期望 React Node 由与 React> React-Calendar 捆绑的类型定义?我确实有@type/react-dom 安装为DEV依赖关系。

可能相关的其他信息:

  1. 该项目直到几天前才进行编译,并且当编译开始失败时,没有代码更改,因此我怀疑包装更新触发了这一点(即使这不是根本原因)。在编译开始失败失败时在时间窗口中更新的唯一依赖项是@type/react 。但是,将这些软件包滚动回旧版本并不能解决问题。
  2. 更改我的组件渲染方法以返回 JSX.Element 删除编译器错误,但是应用程序中有第三方组件无法实现。

I have a React Typescript application that won't compile. Many components have a render method that is typed to return React.ReactNode or React.ReactElement. On compile, many errors similar to the following are reported:

TS2786: 'MessagesWidget' cannot be used as a JSX component.
 Its instance type 'MessagesWidget' 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/node/app/node_modules/@types/react-calendar/node_modules/@types/react/index").ReactNode'.

Why is the compiler expecting ReactNode as defined by the types bundled with react-calendar? I do have @types/react-dom installed as a dev dependency.

Other information that might be relevant:

  1. This project was compiling until a couple of days ago and there were no code changes when the compile started failing, so I suspect that a package update triggered this (even if that's not the root cause). The only dependencies that were updated in the time window when the compile started failing were @types/react and @types/react-dom. Rolling these packages back to an older version did not fix the issue, however.
  2. Changing my components render methods to return JSX.Element removes the compiler error, but there are third party components in the application where this is not possible.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

孤独岁月 2025-01-27 13:32:45

我有一个解决方案,似乎 18.0.1 类型定义中有大量破坏性更改。

和你一样,我无法通过回滚到早期版本来解决这个问题,但调查让我发现这是因为“react-router”等引入了“18.0.1”版本。

为了解决这个问题,我将以下内容添加到我的 package.json

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

然后我清除了我的节点模块和包缓存,然后重新运行纱线以提取新的包。

分辨率部分适用于纱线(我使用的)。我认为如果您使用 NPM,您可以使用“覆盖”而不是“分辨率”。

npm 版本应该 >= 8
https://docs.npmjs.com/cli/v8/configuring -npm/package-json#overrides

并在 npm i 之前删除 package-lock.json。

I have a solution, it seems that there are a ton of breaking changes in the 18.0.1 type definitions.

Like you, I could not solve it by rolling back to earlier versions, but investigation lead me to discover that this was because 'react-router' among others was bringing in the '18.0.1' version.

to get around this, I added the following to my package.json

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

Then I cleared my node-modules, and my package cache and then re-ran yarn to pull fresh packages.

The resolutions section is for yarn (which I use). and I think you can use 'overrides' instead of 'resolutions' if you are using NPM.

npm version should >= 8
https://docs.npmjs.com/cli/v8/configuring-npm/package-json#overrides

and delete package-lock.json before npm i.

再见回来 2025-01-27 13:32:45

错误 TS2786 通常来自于 @types/react 中的不匹配

当您的库依赖于特定版本的 @types/react(即 v17.0.47),并且您还有其他库使用不同主要版本的 @types/react (即 v18.0.14),那么在使用 React.ReactNodeJSX.Element 时可能会导致兼容性问题。 JSX.Element 类型通常由 React 函数组件返回。

您可以通过简化对 @types/react 的依赖关系来解决该问题,以便它们遵循相同的主要版本。您可以通过执行 npm treat @types/react 来查找项目中依赖于 @types/react 的所有库(当 package-lock.json > 文件存在)或 yarn Why @types/react (当 yarn.lock 文件存在时)。

在您的具体情况下,似乎存在从 @types/react-calendar@types/react 的依赖关系。您的问题似乎是您的项目中存在使用不同版本的 @types/react 的其他依赖项。也许您甚至直接依赖于 @types/react ,其中确切的版本号与 @types/react 所需的 @types/react 版本不同 -日历

此视频展示了如何检查所应用的 @types/ 版本在您自己的项目中做出反应。

Error TS2786 often comes from a mismatch in @types/react.

When you have libraries that are dependent on a specific version of @types/react (i.e. v17.0.47) and you have other libraries working with a different major version of @types/react (i.e. v18.0.14), then this can cause compatibility issues when using React.ReactNode or JSX.Element. The type JSX.Element is usually returned by a React Function Component.

You can solve the problem by streamlining your dependencies on @types/react, so that these follow the same major version. You can find all libraries depending on @types/react in your project by executing npm explain @types/react (when a package-lock.json file is present) or yarn why @types/react (when a yarn.lock file is present).

In your specific case there seems to be a dependency from @types/react-calendar to @types/react. Your problem seems to be that there are other dependencies in your project using a different version of @types/react. Maybe you even have a direct dependency on @types/react where the exact version number is different from the @types/react version required by @types/react-calendar.

Here is a video that shows how to inspect the applied version of @types/react in your own project.

窝囊感情。 2025-01-27 13:32:45

当返回儿童

export const Component = ({ children }) => {
    //...do stuff
    return children
}

要修复时,可能会发生这种情况:

return <>{children}</>

我相信这是因为儿童可能是一系列元素,我们只允许我们返回单个元素元素。这种错误的通常消息是:

JSX表达式必须具有一个父元素。

This can occur when returning children:

export const Component = ({ children }) => {
    //...do stuff
    return children
}

To fix, wrap in a fragment:

return <>{children}</>

I believe this is because children may be an array of elements and we are only allowed to return a single element. The usual message for this kind of error is:

JSX expressions must have one parent element.

我也只是我 2025-01-27 13:32:45

如果有 yarn 用户在附近闲逛;谁最近在进行react/react-native版本升级后遇到了这个问题;只需删除现有的yarn.lock文件即可node_modules 文件夹并再次运行 yarn install 这对我有用。 :)

If there's a yarn user wandering around; who had this issue after doing a react/react-native version upgrade recently; just delete the existing yarn.lock file & the node_modules folder and run yarn install again is what worked for me. :)

○愚か者の日 2025-01-27 13:32:45

在 .tsconfig.json 中添加以下内容 -->编译器选项

"compilerOptions": {
    "paths": {
      "react": [ "./node_modules/@types/react" ]
    }
 }

Add below in .tsconfig.json --> compilerOptions

"compilerOptions": {
    "paths": {
      "react": [ "./node_modules/@types/react" ]
    }
 }
于我来说 2025-01-27 13:32:45

上面的答案都没有解决我的相同打字稿错误 TS2786 的情况
我如何让它工作是将 tsconfig.json

{
  "compilerOptions": {
    "preserveSymlinks": true,
    ...

更新为

{
  "compilerOptions": {
    "preserveSymlinks": false,
    ...

或只是将其删除

None of the answers above solved my case for the same typescript error TS2786
how I get it work is update tsconfig.json

from

{
  "compilerOptions": {
    "preserveSymlinks": true,
    ...

to

{
  "compilerOptions": {
    "preserveSymlinks": false,
    ...

or just simply remove it

情话墙 2025-01-27 13:32:45

将 React Native 从 0.66.3 更新到 0.70.6 后,我遇到了同样的问题。我通过更改 package.json 中的“分辨率”解决了问题。

"resolutions": {
    // "@types/react": "^17" remove this
    "@types/react": "^18.0.8" //adding this
},

更改后,删除 node_modules 目录并运行 npm iyarn

After updating React Native from 0.66.3 to 0.70.6, I faced the same issue. I solved the problem by changing the "resolutions" in the package.json

"resolutions": {
    // "@types/react": "^17" remove this
    "@types/react": "^18.0.8" //adding this
},

After changing this, remove node_modules directory and run npm i or yarn.

眼前雾蒙蒙 2025-01-27 13:32:45

此问题在 @types/react版本中的不匹配 ts2786

npm dedupe 纱dedupe

This issue comes with mismatch in @types/react versions TS2786

Fix it with npm dedupe or yarn dedupe

靑春怀旧 2025-01-27 13:32:45

更新到@types/react最新版本(18)后出现问题。许多 React 库依赖于带有通配符“*”的 @types/react,导致它们在安装模块或创建构建时自动升级到版本 18。如果代码未更新以支持版本 18,这可能会导致兼容性问题。

识别问题很棘手,因为 package.json 文件中可能看起来没有任何更改,但问题在于由于通配符依赖,自动升级到 @types/react 版本 18。

要在包更新之前解决此问题,您可以强制使用旧版本的 @types/react。如果您使用 Yarn,您可以将其添加到您的 package.json 中:

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

The problem arose after updating to the latest version (18) of @types/react. Many React libraries depend on @types/react with a wildcard "*", causing them to automatically upgrade to version 18 when installing modules or creating builds. This can lead to compatibility issues if the code isn't updated to support version 18.

Identifying the issue was tricky because it might appear that nothing changed in the package.json file, but the problem lies in the automatic upgrade to @types/react version 18 due to the wildcard dependency.

To resolve this until the packages are updated, you can force the use of the older version of @types/react. If you're using Yarn, you can add this to your package.json:

"resolutions": {
    "@types/react": "18.0.26",
    "@types/react-dom": "18.0.26"
}
天赋异禀 2025-01-27 13:32:45

如果您使用的是一些较旧的基于React的库,则您的React类型中可能存在不匹配。
尝试将其添加到您的tsconfig.json(“ compileroptions”):

"paths": {
    "react": [ "./node_modules/@types/react" ]
}

If you are using some older React based libraries, maybe there is a mismatch in your React types.
Try adding this to your tsconfig.json ("compilerOptions"):

"paths": {
    "react": [ "./node_modules/@types/react" ]
}
作死小能手 2025-01-27 13:32:45

如果您没有添加@types/react,请先添加:

yarn add --dev @types/react

If you didn't add @types/react, please add it first by:

yarn add --dev @types/react
风筝有风,海豚有海 2025-01-27 13:32:45

只需在 package.json 中添加最新版本的react和react-dom,然后运行以下命令即可重新安装react和react-dom

,在发布此答案时,最新版本的react和react-dom是18。

步骤-

  1. 删除<项目的strong>package-lock.json 文件
  2. 打开项目的package.json
  3. 替换react和react-dom版本
"@types/react": "^18",

“@types/react-dom”:“^18”

4.运行命令

npm install --save-dev @types/react @types/react-dom

完成。它解决了我的问题。

Just add the latest version of react and react-dom in package.json and run below command to re-install react and react-dom

Here , while posting this answer, latest version of react and react-dom is 18.

Steps-

  1. Remove package-lock.json file of your proect
  2. Open package.json of your project.
  3. replace react and react-dom version
"@types/react": "^18",

"@types/react-dom": "^18"

4.Run command

npm install --save-dev @types/react @types/react-dom

Done. It resolved my issue.

影子是时光的心 2025-01-27 13:32:45

我通过将 tsconfig.json 中的 ``jsx: 'react' 更改为 jsx:react-jsx 解决了这个问题

I resolved this issue by changing ``jsx: 'react' in tsconfig.json into jsx:react-jsx

撩心不撩汉 2025-01-27 13:32:45

我会讲一下react-native项目。
所有这些答案都没有帮助我。
但我在我的项目中找到了这个问题的原因。
我忘记填写 tsconfig.json 中的“types”参数。

添加

"types": ["react-native", "jest"]

对我有帮助。
干杯!

I will tell about the react-native project.
All these answers didn't help me.
But I found out the reason for this issue in my project.
I forgot to fill "types" parameter in tsconfig.json.

Adding

"types": ["react-native", "jest"]

helped me.
Cheers!

﹂绝世的画 2025-01-27 13:32:45

就我而言,我一直在面临以下环境工作的问题:

  • npm:10.5.2
  • 节点:v20.13.1
  • Intellij webstorm:2023.3.3
  • React:18.3.1
  • React-dom:18.3.1
  • @types/types/react:18.3.3 .2
  • @types/react-dom:18.0.11
  • @types/node:18.14.6
  • 打字稿:4.9.5

我升级了 @type/node/node 和 typescript

  • @types/node: 20.12.11
  • typescript: 5.4。 5

In my case I've been facing this problem working with the following environment:

  • npm: 10.5.2
  • node: v20.13.1
  • IntelliJ WebStorm: 2023.3.3
  • react: 18.3.1
  • react-dom: 18.3.1
  • @types/react: 18.3.2
  • @types/react-dom: 18.0.11
  • @types/node: 18.14.6
  • typescript: 4.9.5

The problem disappeared when I have upgraded the @types/node and typescript:

  • @types/node: 20.12.11
  • typescript: 5.4.5
深巷少女 2025-01-27 13:32:45

问题是因为 React-Route v18不支持 react-virtualized ,因此应降级。

因此,简单的方法是降级您的路线如下:

"@types/react": "17.0.0",
"@types/react-dom": "17.0.0"

然后,您的应用程序应正常工作。

The problem is because react-route v18 does not support react-virtualized and it should be downgraded.

So the simple way is to downgrade your route as below:

"@types/react": "17.0.0",
"@types/react-dom": "17.0.0"

Then, your app should work properly.

夏九 2025-01-27 13:32:45

我遇到了关于这个错误的同样的问题。我将以下代码添加到我的 package.json 文件中并得到解决。

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

I was facing the same issue about this error. I add the below code to my package.json file and got resolved.

"resolutions": {
  "@types/react": "17.0.2",
  "@types/react-dom": "17.0.2",
  "graphql": "^16.5.0"
},
Oo萌小芽oO 2025-01-27 13:32:45

如果您以前有针对React 17的分辨率:

"resolutions": {
    "@types/react": "^17.0.0"
 },

它会在更新时生成一个包装锁/纱锁的条目,该条目将不会删除。因此,您需要删除此分辨率和纱线锁定条目。
看起来像这样:

"@types/react@*", "@types/[email protected]", "@types/react@^17":
  version "17.0.21"
  resolved "https://registry.yarnpkg.com/@types/react/-/react-17.0.21.tgz#069c43177cd419afaab5ce26bb4e9056549f7ea6"
  integrity something
  dependencies:
    "@types/prop-types" "*"
    "@types/scheduler" "*"
    csstype "^3.0.2"

删除两者并再次运行安装应解决您的问题

If you previously had a resolution for react 17:

"resolutions": {
    "@types/react": "^17.0.0"
 },

it generates an entry in package-lock/yarn lock that won't be removed when you update. So you need to remove this resolution and the yarn lock entry.
It looks like this:

"@types/react@*", "@types/[email protected]", "@types/react@^17":
  version "17.0.21"
  resolved "https://registry.yarnpkg.com/@types/react/-/react-17.0.21.tgz#069c43177cd419afaab5ce26bb4e9056549f7ea6"
  integrity something
  dependencies:
    "@types/prop-types" "*"
    "@types/scheduler" "*"
    csstype "^3.0.2"

Removing both and running install again should solve your problem

℡寂寞咖啡 2025-01-27 13:32:45

对我来说,我错误地将异步添加到了反应组件中。将其删除并在React组件中创建我的异步功能修复了我的。

export async const Component = () => {
   
}

export const Component = () => {
    const asyncFunction = async () => {
}}

For me, I mistakenly added async to the react component. Removing it and creating my async function inside the react component fixes mine.

export async const Component = () => {
   
}

to

export const Component = () => {
    const asyncFunction = async () => {
}}
淡写薰衣草的香 2025-01-27 13:32:45

看来TypeScript在异步组件上遇到麻烦,期望JSX,但没有承认承诺。为了解决这个问题,有些是类型铸造组件并导出铸造版本。一个解决方法是使用 @ts-expect-error指令忽略与异步组件暂时相关的打字稿错误。但是,一旦Typescript更新其类型,该指令可能会变得不必要。此问题的修复程序可能可能包括在下一个打字稿插件更新中。

<div>
  {/* @ts-expect-error Server Component */}
  other codes ... 
</div>

It appears that TypeScript is having trouble with async components, expecting JSX but not recognizing Promise. To address this, some are type casting the component and exporting the casted version. One workaround is to use the @ts-expect-error directive to ignore TypeScript errors related to async components temporarily. However, once TypeScript updates its types, this directive might become unnecessary. The fix for this issue could potentially be included in the next TypeScript plugin update.

<div>
  {/* @ts-expect-error Server Component */}
  other codes ... 
</div>
梦萦几度 2025-01-27 13:32:45

就我而言,这种情况发生在我的一个新的 react-native 项目中。这就是为什么这如此令人困惑。我的情况的修复确实是,我必须重新安装 @types/react 才能使用最新版本。我不确定为什么 npx react-native@latest init 命令没有使用这些类型的最新版本。

yarn add --dev @types/react

In my case, this happened to me with a fresh react-native project. This is why this was so confusing. The fix in my case was really, I had to re-install @types/react to use the latest version. I'm not sure why the npx react-native@latest init command did not use the latest version of those types.

yarn add --dev @types/react
冰葑 2025-01-27 13:32:45

这是我用来解决这个问题的方法:
如果您的项目是Maven项目,请按照以下步骤:

  1. 添加 ansolutions tovent.json中的字段和 scripts 预启动脚本应用添加的分辨率(如[1]或[2]中指示)

     “分辨率”:{
         “@types/react”:“ 17.0.0”,
         “@type/react-dom”:“ 17.0.0”
     },,
     “脚本”:{
         “ predstall”:“ npm install-package-lock-inly -ignore-scripts&amp; amp; amp; amp npx npm-force-resolutions'',
         “ build:prod”:“ node_envs =生产; npm运行i18n; npm运行i18n:compile; rimraf site/public/dist/dist/&amp; node_options = -max_old_space_size = -4096仅有的”,
         “ build:dev”:“ rimraf网站/public/dist/&amp;&amp; webpack-模式开发-watch”
     },,
     

  2. 转到相应组件的pom.xml文件,然后在&lt; properties&gt;

    中添加prestall脚本

    <properties>
        <npm.preinstall.command>preinstall</npm.preinstall.command>
        <!-- add other properties if applicable -->
    </properties>

添加一个新的部分,以指定执行,在`````````````````````
以下是一个示例:

  <plugins>
      <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <version>1.6.0</version>
          <executions>
              <execution>
                  <id>npm run preinstall scripts</id> 
                  <goals>
                      <goal>exec</goal>
                  </goals>
                  <phase>initialize</phase>
                  <configuration>
                      <executable>npm</executable>
                      <arguments>
                          <argument>run</argument>
                          <argument>${npm.preinstall.command}</argument>
                      </arguments>
                  </configuration>
              </execution>
              <!-- add other applicable executions here -->
          </executions>
      </plugin>
      <!-- add other applicable plugins here --> 
  </plugins>

[1] https://judy-webdecoded.medium.com/component-from-npm-module-cannot-cannot-be-be-be-as-a-a-jsx-component-99e895382041
[2] https://github.com/facebook/react/issues/24304 #issuecomment-1092563688

Here's the approach that I used to solve this :
If your project is a maven project, follow the below steps :

  1. Add a resolutions field inside the package.json and under scripts filed in package.json, add a preinstall script to apply the added resolution (As instructed in [1] or [2])

     "resolutions": {
         "@types/react": "17.0.0",
         "@types/react-dom": "17.0.0"
     },
     "scripts": {
         "preinstall": "npm install --package-lock-only --ignore-scripts && npx npm-force-resolutions",
         "build:prod": "NODE_ENVS=production; npm run i18n; npm run i18n:compile; rimraf site/public/dist/ && NODE_OPTIONS=--max_old_space_size=4096 webpack --mode production --stats=errors-only",
         "build:dev": "rimraf site/public/dist/ && webpack --mode development --watch"
     },
    
  2. Go to the pom.xml file of the corresponding component and add the preinstall script inside <properties>

    <properties>
        <npm.preinstall.command>preinstall</npm.preinstall.command>
        <!-- add other properties if applicable -->
    </properties>

Add a new section to specify the execution, under the maven execution plugin properties inside `````
Following is an example :

  <plugins>
      <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <version>1.6.0</version>
          <executions>
              <execution>
                  <id>npm run preinstall scripts</id> 
                  <goals>
                      <goal>exec</goal>
                  </goals>
                  <phase>initialize</phase>
                  <configuration>
                      <executable>npm</executable>
                      <arguments>
                          <argument>run</argument>
                          <argument>${npm.preinstall.command}</argument>
                      </arguments>
                  </configuration>
              </execution>
              <!-- add other applicable executions here -->
          </executions>
      </plugin>
      <!-- add other applicable plugins here --> 
  </plugins>

[1] https://judy-webdecoded.medium.com/component-from-npm-module-cannot-be-used-as-a-jsx-component-99e895382041
[2] https://github.com/facebook/react/issues/24304#issuecomment-1092563688

寄居者 2025-01-27 13:32:45

与OP无关,但是如果其他任何人在升级样式组件 to V6时都遇到了相同的问题。
现在,它与类型捆绑在一起(如其升级文档中所述)因此,您需要卸载@types/stypled-components

原因:@type/stypled-components 库是指@type/react-native 的类型,这些类型与@types/react的类型冲突。卸载之前,您可以运行 npx npm-why @types/react-native 以查看 @type/eack-native 是否存在,并且哪个库在您卸载了它,以验证类型不再存在。

Not relevant to the OP, but if anyone else comes across the same issue when upgrading styled-components to v6.
It now comes bundled with types (as mentioned in their upgrade docs) so you need to uninstall @types/styled-components.

Reason: the @types/styled-components library refers to types from @types/react-native, and these types clash with the types from @types/react. Before uninstalling, you can run npx npm-why @types/react-native to see if @types/react-native is actually present and which library requires it and again when you uninstalled it to verify that the types are not present anymore.

冷情妓 2025-01-27 13:32:45

在修复了我的子组件的 RETURN 语句后,我的问题得到了解决

return; <form></form>

更改为:

return (<form></form>)

my one got solved after I fixed the RETURN statement of my child component

I had in there:

return; <form></form>

changed to:

return (<form></form>)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文