【问题标题】:Type error when using render when defining table columns in material table React在材质表 React 中定义表列时使用渲染时出现类型错误
【发布时间】:2021-10-15 23:02:34
【问题描述】:

您好我正在使用材料表生成表视图,这里我定义了列:

const columns: TableColumn[] = [
    {
        title: 'TYPE',
        field: 'type_of_action',
        highlight: true,
    },
    {
        title: 'DESCRIPTION',
        field: 'description',
    },
    {
        title: 'REFERENCE ID',
        field: 'reference_id'
    },
    {
        title: 'ENVIRONMENT',
        field: 'environment'
    },
    {
        title: 'SEVERITY',
        field: 'severity'
    },
    {
        title: 'PRIORITY',
        field: 'priority'
    },
    {
        title: 'ACTION',
        field: 'action',
        render: (rowData) => (
            console.log(rowData.priority). <---- error
        ),
    }
];

我在最后几列中使用了渲染。但我在 Intellij 中看到一个错误,例如:

TS2339: Property 'priority' does not exist on type '{}'.

实际上我的代码有效,我可以看到 rowData.priority 在我的控制台中打印出来。

我现在这里的 rowData 是 type{} 并且无法识别优先级

为了解决这个问题,我需要在&lt;MaterialTable&gt;标签内定义它,否则无法识别字段?

但是在标签中放这么多行代码看起来很脏。有什么方法可以将列提取到 const 变量同时避免类型错误?

我的一个想法是首先传递 columns 变量,然后使用map 进行操作,但我不知道该怎么做?

【问题讨论】:

  • priority 是否属于 number 类型?

标签: javascript reactjs material-ui material-table


【解决方案1】:

当类型不同于string 时,尝试将type 属性添加到您的列定义中:

const columns: TableColumn[] = [
{
        title: 'PRIORITY',
        field: 'priority',
        type: 'number'
    }
]

Posible values 是:'boolean', 'numeric', 'date', 'datetime', 'time', 'currency'

您可以在此PR 中找到更多详细信息。

【讨论】:

  • 字段优先级为字符串类型。即使对于所有其他字段,我也会收到错误消息,而不仅仅是 priority
  • 我知道为什么,我需要在标签里面定义它,否则字段无法识别?任何其他避免它的方法,在标签中放置这么多行代码看起来很脏
猜你喜欢
  • 2023-01-27
  • 2021-11-19
  • 1970-01-01
  • 2019-10-18
  • 1970-01-01
  • 2021-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多