动态计算组件高度,在浏览器伸缩下也要有变化的hook

84 阅读1分钟

使用场景:一些需要固定高度单位的组件在浏览器伸缩变化的时候也要实时变化,比如antd4的tree组件 table设置固定高度的场景

import {useState,useEffect} from 'react'


const calcHeight=(id,bottom,minHeight)=>{
   const screenHeight=window.innerHeight
   const element=document.getElementById(id)
   if(element){
    // dom距离顶部的高度
    let topHeight=element.getBoundingClientRect().top
    // 求出自己的高度 如果底部有高度就减去 没有就不减去
    let height=screenHeight-topHeight-(bottom || 10)
    if(minHeight && height<minHeight) height=minHeight || 300
    return height
   }
}
/**
 * @description: 
 * @param {*} id dom的id
 * @param {*} bottom 可选 距离底部高度
 * @param {*} minHeight 可选 最小高度 如果比这个高度小就以最小高度为主
 * @return {*} 这个组件的高度
 * @author: 李思甜
 */
const useHeight=(id,bottom,minHeight)=>{
  const [height,setHeight]=useState()
  useEffect(()=>{
    setHeight(calcHeight(id,bottom,minHeight))
    const setNewHeight=()=>{
      setHeight(calcHeight(id,bottom,minHeight))
    }
    window.addEventListener('resize',setNewHeight)
    return ()=>{
      window.removeEventListener('resize',setNewHeight)
    }
  },[])

  return height
  
}