[React]ResizeObserver使用:监听Dom元素尺寸改变

[React]ResizeObserver使用:监听Dom元素尺寸改变

简单示例:监听外层Div的高度,进而动态调整table的滚动高度

const tableMinHeight = 400
const paginationHeight = 100
const tipHeight = 50
const App = () => {
  const contentRef = useRef<any>(null)
  const [tableHeight, setTableHeight] = useState(300)
  const { t } = useTranslation()

  useEffect(() => {
    if (contentRef.current) {
      const height = contentRef.current.clientHeight
      setTableHeight(height)
    }

    const resizeObserver = new ResizeObserver(entries => {
      for (const entry of entries) {
        if (entry.target === contentRef.current) {
          const height = entry.contentRect.height - paginationHeight - tipHeight
          setTableHeight(Math.max(height, tableMinHeight))
        }
      }
    })

    if (contentRef.current) {
      resizeObserver.observe(contentRef.current)
    }

    return () => {
      if (contentRef.current) {
        resizeObserver.unobserve(contentRef.current)
      }
    }
  }, [])

  return (
    <div
      className="t-px-6 t-pb-6 t-flex t-flex-col t-h-full"
    >
      <div className="t-flex-1 t-flex t-flex-col t-overflow-hidden">
        <div className="t-text-2xl t-font-semibold t-text-color-1">标题内容</div>
        {/* 表格内容 */}
        <div className="t-flex-1" ref={contentRef}>
          <TableCom tableHeight={tableHeight} />
        </div>
      </div>
    </div>
  )
}

export default App

你可能感兴趣的:(react.js,javascript,前端)