组件不能在 React 中用作 JSX 组件
Component cannot be used as a JSX component in React
出现“组件不能用作 JSX 组件”的错误有多种原因:
- 返回 JSX 元素数组而不是单个元素。
- 返回 JSX 元素或组件以外的任何值
null
。 - 具有过时版本的 React 类型。
下面是错误如何发生的示例。
// ⛔️ '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 片段
或div
元素来包装数组。
const App = () => { return ( <> {['a', 'b', 'c'].map(element => { return <h2 key={element}>{element}</h2>; })} </> ); }; export default App;
现在我们的组件返回单个 JSX 元素,因此错误已解决。
您可能还会看到使用了更冗长的片段语法。
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 元素。
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;
App
组件返回undefined
是因为我们将语句return
放在一行,将 JSX 代码放在下一行,而没有使用括号。
undefined
从组件返回,因此会发生错误。To solve the error, make sure the code you are returning is reachable.
const App = () => { return ( <div> <h2>hello world</h2> </div> ); }; export default App;
If you are sure you are returning a single JSX element or null
from your React
component but the error persists, try updating your React typings.
Open your terminal in your project’s root directory (where your package.json
file is located) and run the following command:
# 👇️ 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
The command will update the versions of your react typings.
npm start
command.If the error is not resolved, try to delete your node_modules
and
package-lock.json
(not package.json
) files, re-run npm install
and restart
your 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 经常出现故障,有时重启可以解决问题。