Ant Pro组件——proTable使用总结

4,930 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第1天,点击查看活动详情

columns

1、在查询表单中不想展示该项,使用hideInSearch:true

const columns = [{
  title: '性别',
  key: 'sex',
  dataIndex: 'sex',
  hideInSearch: true,
}]

2、在Table中不想展示此列,使用hideInTable:true

const columns = [{
  title: '性别',
  key: 'sex',
  dataIndex: 'sex',
  hideInTable: true,
}]

3、当返回的数据需要判断处理再展示或要自己写一些方法时,可以借用render, 第一个参数_为dom,第二个参数record返回的是当条所有数据:

const columns = [{
  title: '编号',
  key: 'No',
  dataIndex: 'No',
  render:(_, record: item) => {
    return (
      <Button
        type="link"
        onClick={() => {...}}
      >
        {record.No}
      </Button>
    );
  },
}]

4、搜索项查询时,传参和dataIndex定义的不一致,需要处理,可以借用columns中的search: 这时候查询的入参不再是subjectName,而是senderCustomerId

const columns = [
    {
      title: '归属主体',
      width: 120,
      dataIndex: 'subjectName',
      search: {
        transform: (value: any) => ({
          senderCustomerId: value?.value,
        }),
      },
    },

5、可以设置查询条件的类型,使用valueType,根据不同的值,生成对应的渲染器, 常见的有 date,textarea,select等,默认是text 更多类型,可参考官网:valueType 列表

const columns = [{    title: '开始日期',    dataIndex: 'startTime',    valueType: 'dateTime'}]

6、columns根据不同的枚举,自动生成对应的下拉框,可以使用 valueEnum

const columns = [{ 
    title: '状态', 
    dataIndex: 'status', 
    valueEnum: { 
    0: { text: '已取消', status: 'Default', }, 
    1: { text: '审核中', status: 'Processing', }, 
    2: { text: '成功', status: 'Success', }, 
    3: { text: '异常', status: 'Error', }, },
}]

7、扩展组件,例如想添加校验,增加placeholder, 增加options,可以使用fiedProps:

// 列中定义
const columns = [
  {
    title: '创建者',
    width: 120,
    dataIndex: 'creator',
    valueType: 'select',
    fieldProps: {
      palceholder: '请选择创建者'
      options: [
        {
          label: 'item 1',
          value: 'a',
        },
        {
          label: 'item 2',
          value: 'b',
        }
      ],
    },
  },
];

8、如果对查询还有别的需求,可以使用formItemProps,

{
    title: '客户',
    dataIndex: 'customer',
    render: (_, record) => {
      return record.customer;
    },
    renderFormItem: (_, {}, form) => {
      return (
        <OriginSelect
          allowClear
          showSearch
          showAllOptions
          placeholder="请选择"
          request={...}
        />
      );
    },
  },

Origin是可以支持搜索查询的一个选择下拉框

9、ellipsis和width不能同时使用,使用width,会自动换行,但是英文不行

需要加上word-break: break-word;

一些基本用法

1、如果不想要查询条件,可以使用search={false}

<ProTable search={false}>

2、默认展开查询的条件

<ProTable search={{ collapsed: false}} />

如果要去掉收起,使用 collapseRender:() => null

3、需要刷新当前table,可以使用actionRef

const ref = useRef<ActionType>();

<ProTable actionRef={ref} />;

// 刷新
ref.current.reload();

// 刷新并清空,页码也会重置,不包括表单
ref.current.reloadAndRest();

// 重置到默认值,包括表单
ref.current.reset();

// 清空选中项
ref.current.clearSelected();

// 开始编辑
ref.current.startEditable(rowKey);

// 结束编辑
ref.current.cancelEditable(rowKey);