类型 'Element[]' 缺少类型 'Element' 中的以下属性:type、props、key

Rom*_*man 31 typescript reactjs

我有带有 Typescript 和 React 环境的标准箭头映射 ES7 函数:

 const getItemList: Function = (groups: any[]): JSX.Element => 
  group.map((item: any, i: number) => {
    const itemCardElemProps = { handleEvents: () => {}, ...item}
    return <Item key={`${item.id}_${i}`} {...itemCardElemProps} />
  })
Run Code Online (Sandbox Code Playgroud)

并得到错误:

TS2739: Type 'Element[]' is missing the following properties from type 'Element': type, props, key
Run Code Online (Sandbox Code Playgroud)

版本:打字稿 3.5.3

and*_*.in 28

您也可以始终将单个 JSX.Element 作为片段发回:

interface IOptions {
   options: string[]
}

const CardArray: React.FC<IOptions> = ({ options }) => {
   return <>{options.map(opt => opt)}</>
}
Run Code Online (Sandbox Code Playgroud)

这样您就可以匹配返回的类型,并且不会影响您的标记。


Rom*_*man 25

要修复错误,有必要将函数输出的类型从 更改JSX.ElementJSX.Element[]如下所示:

 const getItemList: Function = (groups: any[]): JSX.Element[] => 
  group.map((item: any, i: number) => {
    const itemCardElemProps = { handleEvents: () => {}, ...item}
    return <Item key={`${item.id}_${i}`} {...itemCardElemProps} />
  })
Run Code Online (Sandbox Code Playgroud)


ati*_*ker 7

我收到错误是因为我继承了 JSX.Element 但我使用了 .ts 文件扩展名。当我使用 .tsx 文件扩展名时,我的问题得到解决。

在此输入图像描述


小智 5

@Roman 他们一定改变了一些东西,这对我不起作用

代码:

const CardArray = (props: Items): JSX.Element[] => {
    return props.items.map((item) => <Item data={item} />);
};

export default CardArray;

Run Code Online (Sandbox Code Playgroud)

错误:

JSX element type 'Element[]' is not a constructor function for JSX elements.
Type 'Element[]' is missing the following properties from type 'Element': type, props, key
Run Code Online (Sandbox Code Playgroud)

编辑:没关系,我只需要将函数类型添加到函数中......如果你问我的话有点愚蠢。

什么对我有用:

JSX element type 'Element[]' is not a constructor function for JSX elements.
Type 'Element[]' is missing the following properties from type 'Element': type, props, key
Run Code Online (Sandbox Code Playgroud)

  • 这也对我有帮助。不明白为什么但是谢谢! (3认同)