antdesign table 滚动高度自适应

文章介绍了在基于React和AntD的管理端列表页中,如何根据浏览器窗口高度动态设置表格的滚动条最大高度,以实现跨浏览器的适配。方法涉及使用useState和useEffectHook来计算并设置表格滚动高度。
摘要由CSDN通过智能技术生成

基于react + antd 项目框架开发的管理端列表页,通常需要根据浏览器窗口动态设置表格列表出现滚动条的最大高度scroll.y属性进行浏览器适配。

通用方法:

/**
  * 获取第一个表格的可视化高度
  * @param {*} extraHeight 额外的高度(表格底部的内容高度 Number类型,默认为74) 
  * @param {*} id 当前页面中有多个table时需要制定table的id
  */
export const getTableScroll = (params: { extraHeight?: number, id?: string }) => {
  let extraHeight = params?.extraHeight;
  if (typeof extraHeight == "undefined") {
    //  默认底部边距20
    extraHeight = 0;
  }
  let tHeader = null
  if (params?.id) {
    const { id } = params;
    tHeader = document.getElementById(id) ? document.getElementById(id).getElementsByClassName("ant-table-thead")[0] : null
  } else {
    tHeader = document.getElementsByClassName("ant-table-thead")[0];
  }
  //表格内容距离顶部的距离
  let tHeaderBottom = 0;
  if (tHeader) {
    tHeaderBottom = tHeader.getBoundingClientRect().bottom;
  }

  //窗体高度-表格内容顶部的高度-表格内容底部的高度
  let height = `calc(100vh - ${tHeaderBottom + extraHeight}px)`;
  return height;
}

table 组件:

const TableCom: React.FC<TableProps> = (props) => {

  const { dataSource, columns, loading, extraHeight, ...otherprops } = props;

  // 表格滚动高度
  const [scrollY, setScrollY] = useState<any>();

  useEffect(() => {
    const calcScrollY = getTableScroll({ extraHeight: extraHeight || 20 });
    setScrollY(calcScrollY);
  }, []);

  return (
    <div className={styles.table}>
      <Table
        className={styles.tableClass}
        dataSource={dataSource}
        columns={columns}
        scroll={{ y: scrollY }}
        loading={loading}
        {...otherprops}
      />
    </div>
  )
}
export default TableCom;

需要注意:

1.需要固定表格父容器的总高度

.table {
  width: 100%;
  height: 100%;
  position: relative;

  .tableClass {
    height: 100%;
  }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值