• 组件自适应页面高度


    代码

    
    import React, { useRef, useEffect, useState } from 'react';
    import ReactDOM from 'react-dom';
    
    // export interface AutoRestHeightProps extends HTMLAttributes<Element> {
    //   diff: number;  // 差距间隙,可以用作微调
    //   topSelector: string; // 内部 top 位置的 query selector
    // }
    
    /**
     * 自动适应高度
     */
    const AutoRestHeight = ({ children, diff = 80, topSelector, style }) => {
      const childrenRef = useRef(null);
      const frame = useRef(0);
      const [height, setHeight] = useState('auto');
    
      useEffect(() => {
        const resize = () => {
          if (childrenRef.current) {
            // eslint-disable-next-line
            const childrenRefWrapperDom = ReactDOM.findDOMNode(childrenRef.current);
            let childrenRefDom = childrenRefWrapperDom;
            if (topSelector) {
              childrenRefDom = childrenRefDom.querySelector(topSelector);
            }
            const { top: offsetTop } = childrenRefDom.getBoundingClientRect();
            setHeight(window.innerHeight - offsetTop - diff);
            if (childrenRef.current.handleResize) {
              childrenRef.current.handleResize();
            }
          }
        };
        resize();
        const handler = () => {
          cancelAnimationFrame(frame.current);
          frame.current = requestAnimationFrame(resize);
        };
        window.addEventListener('resize', handler);
        return () => {
          cancelAnimationFrame(frame.current);
          window.removeEventListener('resize', handler);
        };
      }, []);
    
      if (React.isValidElement(children)) {
        return React.cloneElement(children, {
          ref: childrenRef,
          style: {
            ...style,
            height,
          },
        });
      } else {
        return null;
      }
    };
    
    export default AutoRestHeight;
    
    
    

    使用方式

    
    <AutoRestHeight topSelector=".c7n-pro-table">
        <Table
            dataSet={this.props.tableDS}
            columns={this.columns}
            buttons={this.buttons}
        />
    </AutoRestHeight>
    
    

    属性介绍