You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

useDomSize.ts 1.2 kB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { debounce } from 'lodash';
  2. import { useEffect, useRef, useState } from 'react';
  3. /**
  4. * 用于追踪 DOM 元素尺寸的 hook。
  5. *
  6. * @param initialWidth - 初始宽度。
  7. * @param initialHeight - 初始高度。
  8. * @param deps - 依赖列表。
  9. * @return 一个元组,包含 DOM 元素的 ref、当前宽度和当前高度。
  10. */
  11. export function useDomSize<T extends HTMLElement>(
  12. initialWidth: number,
  13. initialHeight: number,
  14. deps: React.DependencyList = [],
  15. ) {
  16. const domRef = useRef<T>(null);
  17. const [width, setWidth] = useState(initialWidth);
  18. const [height, setHeight] = useState(initialHeight);
  19. useEffect(() => {
  20. const setDomHeight = () => {
  21. if (domRef.current) {
  22. setHeight(domRef.current.offsetHeight);
  23. setWidth(domRef.current.offsetWidth);
  24. }
  25. };
  26. const debounceFunc = debounce(setDomHeight, 100);
  27. setDomHeight();
  28. window.addEventListener('resize', debounceFunc);
  29. return () => {
  30. window.removeEventListener('resize', debounceFunc);
  31. };
  32. // eslint-disable-next-line react-hooks/exhaustive-deps
  33. }, deps);
  34. return [domRef, { width, height }] as const;
  35. }