生在红旗下 發表於 2020-1-21 15:21:00

React+Antd封装的简易的编辑表格

<h4 id="前言">前言</h4>
<blockquote>
<p>因为项目需要,需要一个可编辑的表格,但是Antd中提供的可编辑表格实在是太繁琐,使用起来实在是太不友好了,所以自己就写了一个简易的编辑表格组件。</p>
</blockquote>
<h4 id="第一步">第一步</h4>
<p>首先,在项目中创建一个<code>EditTable.tsx</code>的文件;在文件中引入需要的模块;</p>
<blockquote>
<p>PS:本人使用的React Hook + TypeScript来进行开发的;</p>
</blockquote>
<pre><code class="language-jsx">import React, { useState, useEffect } from 'react';
import { Table, Form, message, Input } from 'antd';   //需要的antd的组件
import { FormComponentProps } from 'antd/lib/form';
import { ColumnProps } from 'antd/lib/table';
import { dataItemType } from './interface';//定义

/**
* 定义需要的数据的类型
*/
interface EditTableProps extends FormComponentProps {
dataSource: dataItemType[];
loading: boolean;
}
</code></pre>
<h4 id="第二步">第二步</h4>
<p>编写组件</p>
<pre><code class="language-jsx">const EditTable: React.FC&lt;EditTableProps&gt; = ({loading, dataSource, form: {getFieldDecorator}}) =&gt; {
const = useState&lt;dataItemType[]&gt;();//用来存储编辑后的数据, 用来传递给后台
const = useState&lt;dataItemType&gt;();//用来展示编辑后的数据   

useEffect = () =&gt; {
    //将传入的数据浅拷贝一下,避免在子组件中直接修改父组件传入的 dataSource
    setData([...dataSource]);
    setEditData([...dataSource]);
,[]};

/**
   * 列表表头数组
   */
const columns: Array&lt;ColumnProps&lt;dataItemType&gt;&gt; = [
    {
      title: '单据',
      dataIndex: 'record'
    },
    /*........*/
    {
      title: '编辑',
      dataIndex: 'edit',
      render: (text: any, record: any, index: number) =&gt; {
          return (
            &lt;Form&gt;
            {getFieldDecorator(`countNum[${index}]`, {
                rules: [
                  {
                  required: true,
                  message: '编辑字段不能为空',
                  },
                  
                ],
            })(
                &lt;Input
                  onChange={e =&gt; {
                  textChange(e, record);
                  }}
                /&gt;
            )}
            &lt;/Form&gt;
          );
    },
]

return (
    &lt;Table columns={columns} dataSource={data} pagination={false} loading={loading} rowKey='id'/&gt;
)
}

export default Form.create&lt;EditTableProps&gt;()(EditTable)
</code></pre>
<h4 id="第三步">第三步</h4>
<p>处理编辑的数据</p>
<pre><code class="language-jsx">const textChange = (e: any, record: any) =&gt; {
    let rows = [...data];
    let row = rows.find(item =&gt; item.id === record.id);
    if (row) {
       row.countNum = e.target.value;
    }
    //保存编辑后的数据
    setEditCacheData(rows);
};
</code></pre>
<p>到此,一个简单的编辑表格组件就已经封装好了,可能还有更好的实现方法,但是当时由于项目事件紧张,只能想出这种实现方法,各位大佬不喜勿喷;</p><br><br>
来源:https://www.cnblogs.com/cuiwenqian/p/12221869.html
頁: [1]
查看完整版本: React+Antd封装的简易的编辑表格