欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

‘App‘ cannot be used as a JSX component. Its return type ‘Element[]‘ is not a valid JSX element.

程序员文章站 2022-04-28 09:05:15
...

记录最近在用ts写react遇到的一个问题:
代码如下:

function App() {
  const nameArray:string[] = ['Bob','Jack','Mary'];
  return(
  nameArray.map((name:string)=>{    
    return(
      <div>{name}</div>
    )
  })
  )
 }

然后报错:
‘App’ cannot be used as a JSX component. Its return type ‘Element[]’ is not a valid JSX element.
‘App‘ cannot be used as a JSX component. Its return type ‘Element[]‘ is not a valid JSX element.

解决办法1:把函数组件App的返回值设置为any类型即可解决。

function App():any {
  const nameArray:string[] = ['Bob','Jack','Mary'];
  return(
  nameArray.map((name:string)=>{    
    return(
      <div>{name}</div>
    )
  })
  )
 }
 export default App;

解决办法2:把函数组件App的返回值改写成JSX元素类型的。
代码如下:

function App():JSX.Element {
  const nameArray:string[] = ['Bob','Jack','Mary'];
  return(
    <div>
    {
      nameArray.map((name:string)=>{
        return(
          <div>{name}</div>
        )
      })
    } 
    </div>
  )
}
export default App;

运行结果:
‘App‘ cannot be used as a JSX component. Its return type ‘Element[]‘ is not a valid JSX element.