背景

公司的后台产品有很多表格,UI要求表格和别的内容一屏展示,表格内容超出部分表格内滚动。antd Table支持添加scroll属性:scroll={{ y: Y }},滚动区域高度为Y,因此需要计算出Y的值,每个表格都需要,因此考虑封装普通Table组件或是使用高阶组件。

高阶组件

https://react.docschina.org/docs/higher-order-components.html

antd table自适应高度

  1. // 高阶组件,可做装饰器
  2. // 计算 窗口高度-WrappedComponent.tableRef距离页面顶部的距离
  3. import React, { Component } from "react";
  4. const TableAdaptive = WrappedComponent => {
  5. return class extends Component {
  6. constructor(props) {
  7. super(props);
  8. this.state = { y: null };
  9. this.ref = WrappedComponent.tableRef;
  10. this.onWindowResize = this.onWindowResize.bind(this);
  11. }
  12. componentDidMount() {
  13. this.onWindowResize();
  14. window.addEventListener("resize", this.onWindowResize);
  15. }
  16. componentWillUnmount() {
  17. window.removeEventListener("resize", this.onWindowResize);
  18. }
  19. // 计算元素距窗口顶端的距离
  20. getAbsTop(node) {
  21. var top = node.offsetTop;
  22. while (node.offsetParent != null) {
  23. node = node.offsetParent;
  24. top += node.offsetTop;
  25. }
  26. return top;
  27. }
  28. onWindowResize() {
  29. if (this.ref && this.ref.current) {
  30. const el = document.body || document.documentElement;
  31. const top = this.getAbsTop(this.ref.current) || 0;
  32. const y = el.clientHeight - top;
  33. this.setState({
  34. y
  35. });
  36. }
  37. }
  38. render() {
  39. const { y } = this.state;
  40. return <WrappedComponent tableData={{ y: y }} {...this.props} />;
  41. }
  42. };
  43. };
  44. export default TableAdaptive;

可直接在页面使用装饰器

  1. @tableAdaptive
  2. class Project extends Component {
  3. static tableRef = React.createRef();
  4. render(){
  5. const {tableData:{Y}={} = this.props;
  6. return <div ref={Project.tableRef}>
  7. <Table
  8. rowKey="id"
  9. size="small"
  10. scroll={{ y: Y - 100 }} // 100是size为small时的表头和表尾
  11. dataSource={data}
  12. columns={columns}
  13. />
  14. </div>
  15. }
  16. }