【问题标题】:Type 'Element[]' is missing the following properties from type 'Element': type, props, key类型“元素 []”缺少类型“元素”的以下属性:类型、道具、键
【发布时间】:2020-02-07 05:19:22
【问题描述】:

我有 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} />
  })

并得到错误:

TS2739: Type 'Element[]' is missing the following properties from type 'Element': type, props, key

版本:打字稿 3.5.3

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    您也可以随时将单个 JSX.Element 作为片段发送回:

    interface IOptions {
       options: string[]
    }
    
    const CardArray: React.FC<IOptions> = ({ options }) => {
       return <>{options.map(opt => opt)}</>
    }
    

    这样你匹配返回的类型,它不会影响你的标记。

    【讨论】:

      【解决方案2】:

      要修复该错误,需要将函数输出的类型从JSX.Element 更改为JSX.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} />
        })
      

      【讨论】:

      • 对我来说,我注意到如果我没有将 const getItemList 声明为此答案中描述的函数,即使我将函数输出定义为 JSX.Element[]JSX.Element 警告仍然存在跨度>
      • 超级解决方案。
      【解决方案3】:

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

      代码:

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

      错误:

      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
      

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

      什么对我有用:

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

      【讨论】:

      • 这对我也有帮助。不明白为什么,但谢谢!
      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2020-12-20
        • 2021-05-11
        • 2022-07-24
        • 1970-01-01
        • 2021-04-20
        • 2021-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多