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

发布于 2025-01-21 07:03:01 字数 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-28 07:03:01

我有一个解决方案,似乎在18.0.1类型定义中发生了大量的破坏变化。

像您一样,我无法通过回到早期版本来解决它,但是调查使我发现这是因为“ React-Router”等正在带来'18 .0.1'版本。

为了解决这个问题,我将以下内容添加到我的包装中。

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

然后我清除了节点模块,以及软件包的缓存,然后重新运行纱线以拉新的包装。

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

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

和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-28 07:03:01

错误ts2786 通常来自@types/react的不匹配

当您的库取决于@types/react (即v17.0.47)的特定版本时,并且您的其他库与其他主要版本的@types/react (即v18.0.14),那么使用 react.reaeactNode jsx.element 时,这可能会引起兼容性问题。类型 JSX.Element 通常由React函数组件返回。

您可以通过在@type/react 上简化依赖项来解决问题,以便遵循相同的主要版本。您可以通过执行 npm divell @type/react (当 package> package> package> package-lock.json @type/react 找到所有库。 >文件存在)或纱线为什么 @types/react (当存在 yarn.lock 文件时)。

在您的具体情况下,似乎从@type/react-calendar @types/react 的依赖性。您的问题似乎是您项目中使用其他版本的@type/react 中还有其他依赖关系。也许您甚至直接依赖@types/react ,其中确切的版本号与@type/react 版本@types/react-要求 - 日历

这是一个视频,它显示了如何检查应用版本的版本React 在您自己的项目中。

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-28 07:03:01

当返回儿童

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-28 07:03:01

如果有纱线用户四处游荡;在做反应/反应本版本升级后,谁遇到了这个问题;只是删除现有 yarn.lock file&amp; node_modules 文件夹和运行纱线安装再次对我有用。 :)

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-28 07:03:01

在.tsconfig.json-&gt;编译

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

Add below in .tsconfig.json --> compilerOptions

"compilerOptions": {
    "paths": {
      "react": [ "./node_modules/@types/react" ]
    }
 }
浊酒尽余欢 2025-01-28 07:03:01

上面的任何答案都没有解决我的案例,以解决相同的打字错误错误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-28 07:03:01

在将React Native从0.66.3更新为0.70.6之后,我遇到了同样的问题。我通过在更改此问题中更改包装中的“分辨率”来解决问题。

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

更改此问题后,删除Node_modules目录并运行 npm i YARN

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-28 07:03:01

此问题在 @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-28 07:03:01

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

确定问题很棘手,因为在 package.json.json 文件中似乎没有任何更改,但是问题在于由于通配符依赖性,自动升级到@types/react 版本18。

为了解决此问题,直到包装更新,您可以强制使用@type/react 的旧版本。如果您使用的是纱线,则可以将其添加到您的 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-28 07:03:01

如果您使用的是一些较旧的基于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-28 07:03:01

如果您没有添加 @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-28 07:03:01

只需在包装中添加最新版本的react和react-dom.json并在下面的命令中运行以重新安装react and react-dom

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

步骤 -

  1. 删除<< strong> package-lock.json 您的Proct
  2. Open package.json 的文件。
  3. 更换React和React-Dom版本
 “@types/react”:“^18”,

“@type/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-28 07:03:01

我通过更改``jsx :'react' in tsconfig.json中解决了这个问题,以 jsx react> react-jsx

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

少女净妖师 2025-01-28 07:03:01

我将讲述反应生态项目。
所有这些答案对我没有帮助。
但是我发现了我项目中此问题的原因。
我忘了在tsconfig.json中填写“类型”参数。

添加

"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-28 07:03:01

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

  • 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-28 07:03:01

问题是因为 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-28 07:03:01

关于这个错误,我面临着同样的问题。我将以下代码添加到我的软件包.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"
},
べ繥欢鉨o。 2025-01-28 07:03:01

如果您以前有针对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-28 07:03:01

对我来说,我错误地将异步添加到了反应组件中。将其删除并在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-28 07:03:01

看来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-28 07:03:01

就我而言,这发生在我身上,是一个新的 react-native 项目。这就是为什么这是如此令人困惑的原因。在我的情况下,修复程序确实是,我必须重新安装@types/react 才能使用最新版本。我不确定为什么 npx react-native@最新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-28 07:03:01

这是我用来解决这个问题的方法:
如果您的项目是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-28 07:03:01

与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-28 07:03:01

孩子组件的返回声明后,我的一个人得到了解决

我修复了我在那里的

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 和您的相关数据。
原文