antd React 实现可编辑表格(v3)

简化版本:

import React, { useState, useEffect } from 'react';
import { Table, Input, Select, Space, Tooltip } from 'antd';
import styler from './index.less';

 const getHash = (len) => {
  let length = Number(len) || 8;
  const arr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.split(
    '',
  );
  const al = arr.length;
  let chars = '';
  while (length--) {
    chars += arr[parseInt(Math.random() * al, 10)];
  }
  return chars;
};

const kpiOpt = [
  { label: '事件属性1', value: 1, key: 1 },
  { label: '事件属性2', value: 2, key: 2 },
  { label: '事件属性3', value: 3, key: 3 },
  { label: '事件属性4', value: 4, key: 4 },
];
const opt = [
  { label: '1', value: 1, key: 1 },
  { label: '2', value: 2, key: 2 },
  { label: '3', value: 3, key: 3 },
  { label: '4', value: 4, key: 4 },
  { label: '5', value: 5, key: 5 },
];

const symbolOpt = [
  { label: '完全匹配', value: '完全匹配', key: 1 },
  { label: '包含', value: '包含', key: 2 },
  { label: '完全匹配', value: '完全匹配', key: 3 },
];
export default function SingleAction(props) {
  const { value = [], onChange } = props;
  const [dataSource, setDataSource] = useState(value);
  useEffect(() => {
    let arr = [];
    for (let i = 1; i < 5; i++) {
      arr.push({
        id: i,
        name: `维度属性${i}`,
        symbol: i % 2 === 0 ? '包含' : '完全匹配',
        value: i * 10,
      });
    }
    setDataSource(arr);
    onChange?.(arr);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const renderInput = (_, record, index, field) => {
    return (
      <Input
        style={{ width: 200 }}
        value={record[field]}
        onChange={(e) => inputChange(e, record, index, field)}
      />
    );
  };

  const renderSelect = (_, record, index, field, opt) => {
    return (
      <Select
        style={{ width: 200 }}
        value={record[field]}
        onChange={(e) => selectChange(e, record, index, field)}
      >
        {opt.map((item) => {
          return (
            <Select.Option value={item.value} key={item.key}>
              {item.label}
            </Select.Option>
          );
        })}
      </Select>
    );
  };

  const inputChange = (e, record, index, field) => {
    const newData = [...dataSource];
    record[field] = e.target.value;
    newData[index] = record;
    setDataSource(newData);
    onChange?.(newData);
  };

  const selectChange = (e, record, index, field) => {
    const newData = [...dataSource];
    record[field] = e;
    newData[index] = record;
    setDataSource(newData);
    onChange?.(newData);
  };

  const toAdd = () => {
    dataSource.push({
      id: getHash(4),
      name: '',
      symbol: '',
      value: '',
    });
    setDataSource([...dataSource]);
    onChange?.([...dataSource]);
  };
  const toRemove = (_, index) => {
    dataSource.splice(index, 1);
    setDataSource([...dataSource]);
    onChange?.([...dataSource]);
  };
  const toCopy = (record, _) => {
    dataSource.unshift({ ...record, id: getHash(4) });
    setDataSource([...dataSource]);
    onChange?.([...dataSource]);
  };
  const columns = [
    {
      title: '',
      dataIndex: 'name',
      key: 'name',
      render: (text, record, index) =>
        renderSelect(text, record, index, 'name', kpiOpt),
    },
    {
      title: '',
      dataIndex: 'symbol',
      key: 'symbol',
      render: (text, record, index) =>
        renderInput(text, record, index, 'symbol'),
    },
    {
      title: '',
      dataIndex: 'value',
      key: 'value',
      render: (text, record, index) =>
        renderSelect(text, record, index, 'value', opt),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      width: 200,
      align: 'right',
      render: (_, record, index) => (
        <div className="handle">
          <Space>
            <Tooltip placement="bottom" title="添加">
              <i
                type="text"
                onClick={() => toAdd(record, index)}
                className="iconfont-ctrl iconadd_form"
              />
            </Tooltip>
            {dataSource.length > 1 && (
              <Tooltip placement="bottom" title="删除">
                <i
                  type="text"
                  onClick={() => toRemove(record, index)}
                  className="iconfont-ctrl iconremove_form"
                />
              </Tooltip>
            )}
            <Tooltip placement="bottom" title="复制">
              <i
                type="text"
                onClick={() => toCopy(record, index)}
                className="iconfont iconcopy1"
              />
            </Tooltip>
          </Space>
        </div>
      ),
    },
  ];

  const getStyle = (data) => {
    if (data && data.length <= 1) {
      return {
        display: 'none',
      };
    }
    return {
      width: '40px',
      justifyContent: 'center',
      display: 'flex',
      alignItems: 'center',
      background: '#f8fbff',
      border: '1px solid rgba(56,128,255,0.05)',
      borderRight: '0px',
    };
  };
  return (
    <>
      <div className={styler.rules_edit_table} style={{ display: 'flex' }}>
        <div style={getStyle(dataSource)}>
          <span>且</span>
        </div>
        <Table
          rowClassName="rules_edit_row"
          rowKey={(record) => record.id}
          dataSource={dataSource}
          columns={props?.columns || columns}
          pagination={false}
          showHeader={false}
          bordered
        />
      </div>
    </>
  );
}

样式代码:

.rules_edit_table {
  :global {
    .rules_edit_row {
      background: #f8fbff;
    }
    .ant-table-tbody > tr > td {
      border-right: 0px !important;
    }
  }
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

superTiger_y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值