ahooks#useAntdTable TypeScript Examples

The following examples show how to use ahooks#useAntdTable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts    From antdp with MIT License 6 votes vote down vote up
function useTable(service: UseTableType[0], options: UseTableType[1]) {

  const { tableProps, search } = useAntdTable(service, {
    defaultPageSize: 20,
    ...options,

  });

  return {
    tableProps: {
      ...tableProps,
      pagination: {
        ...tableProps.pagination,
        showTotal: (total: number) => `总共: ${total} 条`,
      }
    },
    search
  }
 
}
Example #2
Source File: index.tsx    From fe-v5 with Apache License 2.0 5 votes vote down vote up
index = (_props: any) => {
  const history = useHistory();
  const { t, i18n } = useTranslation();
  const [query, setQuery] = useState('');
  const [mine, setMine] = useState(true);
  const [days, setDays] = useState(7);
  const { curBusiItem } = useSelector<RootState, CommonStoreState>((state) => state.common);
  const { tableProps } = useAntdTable((options) => getTableData(options, curBusiItem.id, query, mine, days), { refreshDeps: [curBusiItem.id, query, mine, days] });
  const columns: ColumnProps<DataItem>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 100,
    },
    {
      title: t('task.title'),
      dataIndex: 'title',
      width: 200,
      render: (text, record) => {
        return <Link to={{ pathname: `/job-tasks/${record.id}/result` }}>{text}</Link>;
      },
    },
    {
      title: t('table.operations'),
      width: 150,
      render: (_text, record) => {
        return (
          <span>
            <Link to={{ pathname: '/job-tasks/add', search: `task=${record.id}` }}>{t('task.clone')}</Link>
            <Divider type='vertical' />
            <Link to={{ pathname: `/job-tasks/${record.id}/detail` }}>{t('task.meta')}</Link>
          </span>
        );
      },
    },
    {
      title: t('task.creator'),
      dataIndex: 'create_by',
      width: 100,
    },
    {
      title: t('task.created'),
      dataIndex: 'create_at',
      width: 160,
      render: (text) => {
        return moment.unix(text).format('YYYY-MM-DD HH:mm:ss');
      },
    },
  ];
  return (
    <PageLayout
      hideCluster
      title={
        <>
          <CodeOutlined />
          {t('执行历史')}
        </>
      }
    >
      <div style={{ display: 'flex' }}>
        <LeftTree></LeftTree>
        {curBusiItem.id ? (
          <div style={{ flex: 1, padding: 10 }}>
            <Row>
              <Col span={16} className='mb10'>
                <Input
                  style={{ width: 200, marginRight: 10 }}
                  prefix={<SearchOutlined />}
                  defaultValue={query}
                  onPressEnter={(e) => {
                    setQuery(e.currentTarget.value);
                  }}
                  placeholder='搜索标题'
                />
                <Select
                  style={{ marginRight: 10 }}
                  value={days}
                  onChange={(val: number) => {
                    setDays(val);
                  }}
                >
                  <Select.Option value={7}>{t('last.7.days')}</Select.Option>
                  <Select.Option value={15}>{t('last.15.days')}</Select.Option>
                  <Select.Option value={30}>{t('last.30.days')}</Select.Option>
                  <Select.Option value={60}>{t('last.60.days')}</Select.Option>
                  <Select.Option value={90}>{t('last.90.days')}</Select.Option>
                </Select>
                <Checkbox
                  checked={mine}
                  onChange={(e) => {
                    setMine(e.target.checked);
                  }}
                >
                  {t('task.only.mine')}
                </Checkbox>
              </Col>
              <Col span={8} style={{ textAlign: 'right' }}>
                <Button
                  type='primary'
                  ghost
                  onClick={() => {
                    history.push('/job-tasks/add');
                  }}
                >
                  {t('task.temporary.create')}
                </Button>
              </Col>
            </Row>
            <Table
              rowKey='id'
              columns={columns as any}
              {...(tableProps as any)}
              pagination={
                {
                  ...tableProps.pagination,
                  showSizeChanger: true,
                  pageSizeOptions: ['10', '50', '100', '500', '1000'],
                  showTotal: (total) => {
                    return i18n.language == 'en' ? `Total ${total} items` : `共 ${total} 条`;
                  },
                } as any
              }
            />
          </div>
        ) : (
          <BlankBusinessPlaceholder text={t('执行历史')}></BlankBusinessPlaceholder>
        )}
      </div>
    </PageLayout>
  );
}
Example #3
Source File: index.tsx    From scorpio-h5-design with MIT License 4 votes vote down vote up
export default function() {
  const [form] = Form.useForm();
  const [edit, setEdit] = useState<{
    visible: boolean,
    data: Record<string, unknown>,
    type: 'add' | 'edit' | 'detail',
  }>({
    visible: false,
    data: {},
    type: 'add',
  });
  const { tableProps, search, refresh } = useAntdTable(service.getCategoryList, {
    form,
    defaultParams: [
      { current: 1, pageSize: 10 },
      {
        sort: { createdAt: -1 },
      },
    ],
    formatResult(res) {
      res.data.list.forEach((item: any) => delete item.children);
      return res.data;
    },
  });
  const addCategoryReq = useRequest(service.addCategory, {
    manual: true,
  });
  const editCategoryReq = useRequest(service.editCategory, {
    manual: true,
  });
  const deleteCategoryReq = useRequest(service.deleteCategory, {
    manual: true,
  });
  const { submit, reset } = search;

  const add = function() {
    setEdit({
      visible: true,
      data: {},
      type: 'add',
    });
  };
  const cancel = function() {
    setEdit({
      visible: false,
      data: {},
      type: 'add',
    });
  };
  const confirm = async function(values: any) {
    if (edit.type === 'add') {
      await addCategoryReq.run(values);
    }
    if (edit.type === 'edit') {
      await editCategoryReq.run({
        _id: edit.data._id as string,
        name: values.name,
      });
    }
    setEdit({
      visible: false,
      data: {},
      type: 'add',
    });
    await refresh();
  };
  const onEdit = function(data: any) {
    setEdit({
      visible: true,
      data,
      type: 'edit',
    });
  };
  const onDelelte = async function(data: any) {
    await deleteCategoryReq.run({
      _id: data._id,
    });
    setEdit({
      visible: false,
      data: {},
      type: 'add',
    });
    await refresh();
  };
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '操作',
      width: 180,
      render(data: any) {
        return (
          <Space split={<Divider type="vertical" />}>
            <Typography.Link onClick={() => { onEdit(data); }}>修改</Typography.Link>
            <Popconfirm
              title="确认此操作?"
              onConfirm={() => { onDelelte(data); }}
              okText="确认"
              cancelText="取消"
            >
              <Typography.Link type="danger">删除</Typography.Link>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];
  const SearchForm = (
    <div>
      <Form form={form}>
        <Row gutter={24}>
          <Col span={8}>
            <Form.Item label="分类名称" name="name">
              <Input placeholder="name" />
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Form.Item style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button type="primary" onClick={submit}>
              查询
            </Button>
            <Button onClick={reset} style={{ marginLeft: 16 }}>
              重置
            </Button>
          </Form.Item>
        </Row>
      </Form>
    </div>
  );
  return (
    <PageHeader
      className="manage-category"
      ghost={false}
      onBack={() => null}
      title="组件分类管理"
      extra={[
        <Button key="1" type="primary" onClick={add}>
          新增
        </Button>,
      ]}
    >
      {SearchForm}
      <Table columns={columns} rowKey="_id" {...tableProps} />
      <FormRenderDrawer
        type={edit.type}
        visible={edit.visible}
        onCancel={cancel}
        formSchema={formSchema}
        onSubmit={confirm}
        loading={addCategoryReq.loading}
        formData={edit.data}
      />
    </PageHeader>
  );
}
Example #4
Source File: index.tsx    From fe-v5 with Apache License 2.0 4 votes vote down vote up
index = (_props: any) => {
  const { t, i18n } = useTranslation();
  const searchRef = useRef<Input>(null);
  const [query, setQuery] = useState('');
  const { curBusiItem } = useSelector<RootState, CommonStoreState>((state) => state.common);
  const busiId = curBusiItem.id;
  const [selectedIds, setSelectedIds] = useState([] as any[]);
  const { tableProps, refresh } = useAntdTable<any, any>((options) => getTableData(options, busiId, query), { refreshDeps: [busiId, query] });

  function handleTagClick(tag: string) {
    if (!_.includes(query, tag)) {
      const newQuery = query ? `${query} ${tag}` : tag;
      setQuery(newQuery);
      searchRef.current?.setValue(newQuery);
    }
  }

  function handleDelBtnClick(id: number) {
    if (busiId) {
      request(`${api.tasktpl(busiId)}/${id}`, {
        method: 'DELETE',
      }).then(() => {
        message.success(t('msg.delete.success'));
        refresh();
      });
    }
  }

  function handleBatchBindTags() {
    if (!_.isEmpty(selectedIds)) {
      BindTags({
        language: i18n.language,
        selectedIds,
        busiId,
        onOk: () => {
          refresh();
        },
      });
    }
  }

  function handleBatchUnBindTags() {
    if (!_.isEmpty(selectedIds)) {
      let uniqueTags = [] as any[];
      _.each(tableProps.dataSource, (item) => {
        const tags = item.tags;
        uniqueTags = _.union(uniqueTags, tags);
      });
      UnBindTags({
        language: i18n.language,
        selectedIds,
        uniqueTags,
        busiId,
        onOk: () => {
          refresh();
        },
      });
    }
  }

  const columns: ColumnProps<Tpl>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: t('tpl.title'),
      dataIndex: 'title',
      render: (text, record) => {
        return <Link to={{ pathname: `/job-tpls/${record.id}/detail` }}>{text}</Link>;
      },
    },
    {
      title: t('tpl.tags'),
      dataIndex: 'tags',
      render: (text) => {
        return _.map(text, (item) => (
          <Tag color='blue' key={item} onClick={() => handleTagClick(item)}>
            {item}
          </Tag>
        ));
      },
    },
    {
      title: t('tpl.creator'),
      dataIndex: 'create_by',
      width: 100,
    },
    {
      title: t('tpl.last_updated'),
      dataIndex: 'update_at',
      width: 160,
      render: (text) => {
        return moment.unix(text).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: t('table.operations'),
      width: 220,
      render: (_text, record) => {
        return (
          <span>
            <Link to={{ pathname: `/job-tpls/add/task`, search: `tpl=${record.id}` }}>{t('task.create')}</Link>
            <Divider type='vertical' />
            <Link to={{ pathname: `/job-tpls/${record.id}/modify` }}>{t('table.modify')}</Link>
            <Divider type='vertical' />
            <Link to={{ pathname: `/job-tpls/${record.id}/clone` }}>{t('table.clone')}</Link>
            <Divider type='vertical' />
            <Popconfirm
              title={<div style={{ width: 100 }}>{t('table.delete.sure')}</div>}
              onConfirm={() => {
                handleDelBtnClick(record.id);
              }}
            >
              <a style={{ color: 'red' }}>{t('table.delete')}</a>
            </Popconfirm>
          </span>
        );
      },
    },
  ];
  return (
    <PageLayout
      hideCluster
      title={
        <>
          <CodeOutlined />
          {t('自愈脚本')}
        </>
      }
    >
      <div style={{ display: 'flex' }}>
        <LeftTree></LeftTree>
        {busiId ? (
          <div style={{ flex: 1, padding: 20 }}>
            <Row>
              <Col span={14} className='mb10'>
                <Input
                  style={{ width: 200 }}
                  ref={searchRef}
                  prefix={<SearchOutlined />}
                  defaultValue={query}
                  onPressEnter={(e) => {
                    setQuery(e.currentTarget.value);
                  }}
                  placeholder='搜索标题、标签'
                />
              </Col>
              <Col span={10} className='textAlignRight'>
                <Link to={{ pathname: `/job-tpls/add` }}>
                  <Button icon={<PlusOutlined />} style={{ marginRight: 10 }} type='primary' ghost>
                    {t('tpl.create')}
                  </Button>
                </Link>
                <Dropdown
                  overlay={
                    <Menu>
                      <Menu.Item>
                        <Button
                          type='link'
                          disabled={selectedIds.length === 0}
                          onClick={() => {
                            handleBatchBindTags();
                          }}
                        >
                          {t('tpl.tag.bind')}
                        </Button>
                      </Menu.Item>
                      <Menu.Item>
                        <Button
                          type='link'
                          disabled={selectedIds.length === 0}
                          onClick={() => {
                            handleBatchUnBindTags();
                          }}
                        >
                          {t('tpl.tag.unbind')}
                        </Button>
                      </Menu.Item>
                    </Menu>
                  }
                >
                  <Button icon={<DownOutlined />}>{t('table.batch.operations')}</Button>
                </Dropdown>
              </Col>
            </Row>
            <Table
              rowKey='id'
              columns={columns}
              {...(tableProps as any)}
              rowSelection={{
                selectedRowKeys: selectedIds,
                onChange: (selectedRowKeys) => {
                  setSelectedIds(selectedRowKeys);
                },
              }}
              pagination={
                {
                  ...tableProps.pagination,
                  showSizeChanger: true,
                  pageSizeOptions: ['10', '50', '100', '500', '1000'],
                  showTotal: (total) => {
                    return i18n.language == 'en' ? `Total ${total} items` : `共 ${total} 条`;
                  },
                } as any
              }
            />
          </div>
        ) : (
          <BlankBusinessPlaceholder text='自愈脚本' />
        )}
      </div>
    </PageLayout>
  );
}