React 实现table内单元格可编辑

Ant Design中给出了实现的办法,但个人觉得有点略微复杂,且在函数组件中似乎还要改写这部分。所以自己实现了一下这个功能,用于函数组件中。
示例:

const ConfigRule = React.forwardRef(({ getFieldDecorator }, ref) => {
const [dataSource, setDataSource] = useState([]);

const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      width: 50,
    },
    {
      title: '数据源',
      dataIndex: 'source',
      key: 'source',
      width: 150,
    },
    {
      title: '源数据表名',
      dataIndex: 'table_name_sr',
      key: 'table_name_sr',
      width: 300,
      textWrap: 'word-break',
      ellipsis: true, // 处理表头宽度不生效
    },
    {
      title: '目标数据表名',
      dataIndex: 'table_name_tr',
      key: 'table_name_tr',
      width: 300,
      textWrap: 'word-break',
      ellipsis: true, // 处理表头宽度不生效
      render: (text, record) => (
        <Item>
          {
              getFieldDecorator(`targetName.${record.key}`, {// 保证每个元素是唯一
                initialValue: text, //之前试过不用getFieldDecorator在外面包着,而是只用input,发现给input设defaultValue,改变table中的数据,input的值不能重新渲染,显示的还是defaultValue;然后又使用value,发现input框里面的值直接无法改变,所以才用了getFieldDecorator。
              })(
                <Input
                  onPressEnter={e => saveRow(e, record)}
                  onBlur={e => saveRow(e, record)}
                />
              )
            }
        </Item>
      ),
    }
  ];
});

// 保存输入框中的值
function saveRow(e, record) {
  const newData = [...dataSource];
  const index = dataSource.findIndex(item => record.key === item.key);
  newData[index].table_name_tr = e.target.value;
  setDataSource(newData);
}

return (
     <ProTable
        className="mytable"
        columns={columns}
        dataSource={dataSource}
        rowKey="table_name_sr"
        scroll={{ x: 1400 }}
        pagination={{
          pageSizeOptions: ['10', '20', '50', '100'],
          showLessItems: true,
          showQuickJumper: true,
          showSizeChanger: true,
        }}
      />
 )
}
export default ConfigRule;

参考:https://blog.csdn.net/weixin_44471622/article/details/105140287

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值