【问题标题】:How to define an Array of JSX Elements?如何定义 JSX 元素数组?
【发布时间】:2022-09-29 22:23:59
【问题描述】:

我有一个数组,我想用 JSX 元素填充。

例如:

const arrayOfJsxElements : string[] = [];
    
arrayOfJsxElements.push(<div>hi</div>);

不幸的是,这会产生以下错误(意料之中,因为它不是字符串):

\'Element\' 类型的参数不能分配给 \'string\' 类型的参数。 ts(2345)

我尝试了以下方法(成功):

import type { ReactElement } from \'react\'
    
const arrayOfJsxElements : ReactElement[] = [];
    
arrayOfJsxElements.push(<div>hi</div>);

现在我正在寻找一个更简单的解决方案,而不是每次遇到这个问题时都导入一些东西。

我应该为 JSX 元素使用什么类型?

    标签: typescript


    【解决方案1】:

    我已经在 TypeScript 文档中找到了答案:

    https://www.typescriptlang.org/docs/handbook/jsx.html

    正确的类型规范似乎是:

    const arrayOfJsxElements : ReactElement[] = [];
    

    【讨论】:

      猜你喜欢
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      • 1970-01-01
      • 2020-12-07
      相关资源
      最近更新 更多