‘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张图片

解决办法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._第2张图片

你可能感兴趣的:(前端,react.js,前端,typescript)