Skip to content

简易的 React Table 组件

Published: at 10:43 PMSuggest Changes

简易的 react table 组件

Github: simple-react-table

Antd 中的 Table 组件有固定头和固定列的功能,表格还有无限滚动,合并单元格。

我自己手写实现了一下其中的固定头和固定列。

运行效果

代码分析

表格的固定头固定列

Table 组件用了 position: sticky; 实现了固定头和固定列,可以看看简易下面的 demo,打开页面后用 F12 查看代码。

这是固定列部分的代码,更多的代码可以去上面的 Github 项目中查看

其中 style.position = 'sticky'; 设置了当前列固定,style.zIndex = '2'; 设置层级,这样在滚动的时候,这一列可以覆盖在上方,

if (fixed === 'left') {
  style.left = index * 100 + 'px';
} else {
  style.right = (columns.length - 1 - index) * 100 + 'px';
}

这一段代码判断列是在左边还是右边,如果是在左边,就加 css 的 left 属性,然后宽度是可以自定义的。

renderTbodyTree(index, key, props) {
  const { columns, data } = props;
  let rowData = data[index];
  return (
    <tr key={'Tbody_' + key}>
      {columns.map((e, index) => {
        let { fixed } = e;
        let style: any = {};
        if (fixed) {
          style.position = 'sticky';
          style.zIndex = '2';
          style.background = 'black';
          if (fixed === 'left') {
            style.left = index * 100 + 'px';
          } else {
            style.right = (columns.length - 1 - index) * 100 + 'px';
          }
        }
        return (
          <td key={'Tbody' + index} style={style}>
            {rowData[e.dataIndex]}
          </td>
        );
      })}
    </tr>
  );
}

表格无限加载

表格无限加载用了 react-list 组件,运行 npm i react-list 安装依赖

这儿不多做介绍,看文档就可以了,用起来超简单

<ReactList
  itemsRenderer={(items, ref) => this.renderTable(items, ref)}
  itemRenderer={(index, key) => this.renderTbodyTree(index, key, this.props)}
  length={this.props.data.length}
  type='uniform'
  pageSize={100}
/>

后记

项目没用 webpack,也没用 react 脚手架这些的,用的是 parcel,这个我也是第一次听说。

不知道 webpack 还行不行了,听说 vite 将取代 webpack,技术的发展真是日新月异,想想 20 年前电脑和和智能手机是个稀罕货,现在经济条件不错的都可以拥有了。


Previous Post
Linux 配置数据库远程连接:Iptables 开启 3306 端口
Next Post
Jenkins 自动化脚本问题及解决方法