• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

react antd实现树级的可编辑表格,并且可以合并表头

武飞扬头像
前端架构师_555
帮助1

简述

最近公司有个新需求,需要做一个树级的可编辑表格,并且可以合并表头。我尼玛,这么复杂的可编辑表格杂整啊。
大概就是下面图类似的,第一行是树级结构,后面都是可以编辑的
学新通

实现

选择的技术方案:在antd的基础上封装(因为antd 的Table组件支持树级显示,也支持合并表头,)

1、antd Table的前置知识

Table的dataSource属性会把里面有嵌套的数据拍平

const data = [
{
    name:"父级",
    children:[
    {name:"子级1"},
    {name:"子级2"},
    ]
    }
]

antd里面最后使用会变成
const flattenData = [
{name:"父级"},  
{name:"子级1"},
{name:"子级2"},
]

学新通

Table源码

Table的columns属性会把里面有嵌套的数据弄成二维数组

const columns=[
    {
      title: '建设任务',
      dataIndex: 'name',
    },
    {
      title: '到位金额',
          children:[
            {
              title: '合计q填报',
              dataIndex: 'total1',
              width: 220,
            },
            {
              title: '合计w填报',
              dataIndex: 'total2',
              width: 220,
            },
          ]
    },]
    
  const resultColumns = [
  [ {
      title: '建设任务',
      dataIndex: 'name',
    },
    {
      title: '到位金额',
      }
  ],[
  {
              title: '合计q填报',
              dataIndex: 'total1',
              width: 220,
            },
            {
              title: '合计w填报',
              dataIndex: 'total2',
              width: 220,
            },
  ]
学新通

Table处理columns源码

2、最简单的实现
const columns=[
    {
      title: '建设任务',
      dataIndex: 'name',
    },
    {
      title: '到位金额',
          children:[
            {
              title: '合计q填报',
              dataIndex: 'total1',
              width: 220,
              render: (value) => <Input value={value} />
            },
            {
              title: '合计w填报',
              dataIndex: 'total2',
              width: 220,
              render: (value) => <Input value={value} />
            },
          ]
    },]
学新通

这样好像行了,自己render,前面是树级,后面都是可以编辑的。但是这样每次都需要我们自己render,达不到封装的目的。好了,接下来我发现antd 的table 有一个components属性,我们可以自定每一行,每一列。

学新通

Table处理TableComponents源码

3、使用components自定义实现表格的行和列
const tdNewComponent = (
  props
) => {

  if (props?.column?.dataIndex === 'name') {
    return <td className={styles.td} {...props}></td>
  }
  return <td><Input/></td>
  
  }

<Table
dataSource={dataSource}
columns={processedColumns}
  components={{
              body: {
                cell: tdNewComponent,
              },
            }}
          />
学新通

这样使用自定单元格确实一次就解决了每次render的问题

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgagcak
系列文章
更多 icon
同类精品
更多 icon
继续加载