【问题标题】:Apply types in React ant design在 React ant 设计中应用类型
【发布时间】:2021-07-01 08:50:51
【问题描述】:

我正在使用来自 antd design 的 Table。而且,我想键入onChange 函数,该函数在 Table 组件中作为参数传递。

const change = (
  pagination: TablePaginationConfig,
  filters: Record<string, Key[] | null>,
  sorter: SorterResult<RecordType> | SorterResult<RecordType>[]
) => {};

ReactDOM.render(
  <Table onChange={change} columns={columns} dataSource={data} />,
  document.getElementById("container")
);

问题是我无法导入RecordType。如何在不使用any 的情况下正确键入此代码?这是demo

【问题讨论】:

  • 我没有看到 ant design 导出类型 RecordType。这只是一个打字稿泛型。您需要提供自己的类型。像这样:sorter: SorterResult&lt;MyType&gt; | SorterResult&lt;MyType&gt;[]
  • @TwoHorses,你能说明一下你的意思吗?
  • 为传递给dataSource prop 的数据创建一个类型(例如MyType)。然后在SorterResult中使用
  • @TwoHorses,但是如果在我的change 函数中我想使用例如:setData(sorter.field),如何进行。打字稿说:Property 'field' does not exist on type 'SorterResult&lt;MyType&gt; | SorterResult&lt;MyType&gt;[]'.如何解决?
  • 那是因为你将sorter 声明为SorterResult&lt;MyType&gt; | SorterResult&lt;MyType&gt;[],它可以是一个数组,数组没有field

标签: reactjs typescript antd


【解决方案1】:

你不必显式声明change的类型,SorterResult的泛型是dataSource项的类型,你可以通过两种方式隐式声明change的类型。

1.将泛型传递给表格元素

type TDataItem = {
  key1: number;
  key2: string;
}

<Table<TDataItem> onChange={()=>{}} columns={columns} dataSource={[]} />,

2。将泛型传递给列:

import { ColumnProps } from 'antd/lib/table';

...

type TDataItem = {
  key1: number;
  key2: string;
}

...

const columns: ColumnProps<TDataItem>[] = [

<Table onChange={()=>{}} columns={columns} dataSource={[]} />,

【讨论】:

  • 我试图在这里创建一个演示,你能帮忙codesandbox.io/s/multiple-sorter-antd4150-forked-ie0o5?file=/…
  • 我试过SorterResult&lt;{field: string, order: string},但没有帮助
  • ,我得到属性 'field' 在类型 'SorterResult[]'。
  • 现在可以看看了。我在数据中添加了一些键,并声明了dataItem的类型
  • 如果你不想像上面那样声明 dataItem 的类型,你可以试试这个:_________________________________________________________________________ type dataItem = typeof data[0]
【解决方案2】:

您只想让 Table 组件知道您传递给它的数据类型以帮助处理类型。

如果你要更新你的函数,你可以使用你当前数据的形状作为你的类型,你的Table应该指向正确的RecordType

type TableData = typeof data[0];
const change = (
  pagination: TablePaginationConfig,
  filters: Record<string, Key[] | null>,
  sorter: SorterResult<RecordType> | SorterResult<RecordType>[]
) => {};
return <Table<TableData> columns={columns} dataSource={data} onChange={onChange} />;

【讨论】:

    猜你喜欢
    • 2021-04-15
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多