9

React报错之组件不能作为JSX组件使用 - chuckQu

 2 years ago
source link: https://www.cnblogs.com/chuckQu/p/16530551.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

正文从这开始~

组件不能作为JSX组件使用,出现该错误有多个原因:

  1. 返回JSX元素数组,而不是单个元素。
  2. 从组件中返回JSX元素或者null以外的任何值。
  3. 使用过时的React类型声明。

返回单个JSX元素

下面是一个错误如何发生的示例。

// App.tsx

// ⛔️ 'App' cannot be used as a JSX component.
// Its return type 'Element[]' is not a valid JSX element.
// Type 'Element[]' is missing the following properties from type 'ReactElement<any, any>': type, props, key
const App = () => {
  return ['a', 'b', 'c'].map(element => {
    return <h2 key={element}>{element}</h2>;
  });
};

export default App;

代码示例中的问题是,我们返回的是一个JSX元素数组,而不是单个JSX元素。

为了解决这种情况下的错误,我们必须使用React fragment 或者div元素来包裹数组。

// App.tsx

const App = () => {
  return (
    <>
      {['a', 'b', 'c'].map(element => {
        return <h2 key={element}>{element}</h2>;
      })}
    </>
  );
};

export default App;

现在我们的组件返回了单个JSX元素,这样错误就解决了。

当我们需要对子节点列表进行分组而不需要向DOM中添加额外的节点时,就会使用Fragments。

您可能还会看到使用了更加详细的fragments语法。

// App.tsx

import React from 'react';

const App = () => {
  return (
    <React.Fragment>
      {['a', 'b', 'c'].map(element => {
        return <h2 key={element}>{element}</h2>;
      })}
    </React.Fragment>
  );
};

export default App;

你也可以使用div元素来充当包裹器,从组件中返回单个JSX元素。

不要忘记返回值

另一个常见原因是,我们从组件中返回JSX元素或者null以外的任意值,或者忘记返回值。

// ⛔️ 'App' cannot be used as a JSX component.
// Its return type 'undefined' is not a valid JSX element.
const App = () => {
  // 👇️ this returns undefined
  return
  <h2>hello world</h2>
};

export default App;

上述代码示例返回undefined,因为我们把返回语句放在一行,而把JSX代码放在下一行,并且没有使用括号。

我们不允许从组件中返回undefined,因此会出现这个错误。

为了解决该错误,我们必须确保返回的代码是可达的。

const App = () => {
  return (
    <div>
      <h2>hello world</h2>
    </div>
  );
};

export default App;

如果你确信从React组件中,返回了单个JSX元素或者null 。但是错误依旧存在,试着更新React类型声明。

更新React类型声明

在项目的根目录下打开终端,运行以下命令:

# 👇️ with NPM
npm install --save-dev @types/react@latest @types/react-dom@latest

# 👇️ if you also want to update react and react-dom
npm install react@latest react-dom@latest

# ------------------------------

# 👇️ with YARN
yarn add @types/react@latest @types/react-dom@latest --dev

# 👇️ if you also want to update react and react-dom
yarn add react@latest react-dom@latest

该命令将会更新你的react类型声明版本。

确保重启开发服务器,如有必要请重启IDE。开发服务器不会接收这些更改,直到你停止它并重新运行npm start命令。

如果错误还没有被解决,尝试删除node_modulespackage-lock.json(不是package.json)文件,重新运行npm install,重启IDE。

# 👇️ delete node_modules and package-lock.json
rm -rf node_modules
rm -f package-lock.json
rm -f yarn.lock

# 👇️ clean npm cache
npm cache clean --force

npm install

如果错误依旧存在,请确保重启了IDE和开发服务器。VSCode经常出现故障,有时重启就能解决问题。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK