关于react.js:React报错之组件不能作为JSX组件使用

7次阅读

共计 2081 个字符,预计需要花费 6 分钟才能阅读完成。

总览

组件不能作为 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 经常出现故障,有时重启就能解决问题。

正文完
 0