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

记录最近在用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.

上一篇:[Pipy]利用pip2pi搭建本地pypi源


下一篇:学习笔记-React的简单介绍&工作原理