有没有更优雅的方法来监视元素尺寸的变化?

时间:2019-12-13 18:55:45

标签: javascript reactjs dom events resize

更改容器元素的宽度或高度时,我的组件必须更新一些值。我发现有两种方法可以监视此尺寸,但是它们都有局限性:

  1. ResizeObserver(不够好(~73%)浏览器支持)
  2. requestAnimationFrame(频繁调用会导致性能下降)

我的组件看起来像:

const MyComponent = props => {

    const containerRef = useRef();  
    const [ dimensions, setDimensions ] = useState({width: 0, height: 0});



    /**
     * Watch for element dimensions changes
     */
    const checkContainerSizes = () => {
        const newWidth = !!containerRef.current ? containerRef.current.offsetWidth || 0 : 0;
        const newHeight = !!containerRef.current ? containerRef.current.offsetHeight || 0 : 0;

        if( dimensions.width !== newWidth || dimensions.height !== newHeight ) {
            setDimensions({
                width: newWidth,
                height: newHeight
            });

            return true;            
        } else {    
            return false;           
        }
    }

    useEffect( () => {
        if( ResizeObserver in window ) return;

        let unmounted = false;

        const requestCheck = () => {
            window.requestAnimationFrame( () => {
                if( unmounted ) return;

                if( !checkContainerSizes() ) {              
                    requestCheck();
                }
            });
        }
        requestCheck();

        return () => unmounted = true;
    });

    useEffect( () => {
        if( ResizeObserver in window ) {
            const resizeObserver = new ResizeObserver(entries => {
                checkContainerSizes();
            });

            resizeObserver.observe(containerRef.current);

            return () => resizeObserver.disconnect();
        }       
    }, []); 



    /**
     * Update svg element depend on container dimensions
     */
    useEffect( () => {
        // Update actions       
    }, [dimensions]);



    return (
        <div ref={containerRef}>

        </div>
    );
}

问题:是否有更优雅的方法来监视特定元素的调整大小事件?

0 个答案:

没有答案