react 自动设置高度

2023-12-14 22:35:08
export default function Height() {
    const [showDom,setShowDom]=useState([])
    const heightRef = useRef(null)
    let arrData =[
        {
               "index": 1,//占的U位
               "model_id": "assert",//model_id
               "ci_id": 1,//设备id 
               "ci_name": "设备1"//设备名称
             },
             {
               "index": 2,
               "model_id": "assert",
               "ci_id": 1,//设备占的U位多id相同
               "ci_name": ""//设备占的U位多不写名称
             },
             {
               "index": 3,
               "model_id": "assert",
               "ci_id": 1,
               "ci_name": ""
             },
             {
               "index": 4,
               "model_id": "assert",
               "ci_id": 2,
               "ci_name": "设备2"
             },
             {
               "index": 5,
               "model_id": "assert",
               "ci_id": 2,
               "ci_name": ""
             },
             {
               "index": 6,
               "model_id": "assert",
               "ci_id": 2,
               "ci_name": ""
             },
             {
               "index": 7,//没有占用 序号要有
               "model_id": "",
               "ci_id": "",//没有U位id为空
               "ci_name": ""
             }
   ]
   const changeData=(arrData)=>{
    let newArr = []
    arrData.forEach(item => {
        const parent = newArr.find(c => c.ci_id=== item.ci_id)
        if (parent) {
            parent.dataInfo.push(item)
        } else {
            const obj = {
                index: item.index,
                model_id:item.model_id,
                ci_id: item.ci_id,
                ci_name:item.ci_name,
                dataInfo:[item]
            }
            newArr.push(obj)
        }
    })
    newArr.map(obj => {  
      obj.height = obj.dataInfo.length*20+"px";  
      return obj;  
    });  
    return newArr
   }
    useEffect(()=>{
       let arrObj= changeData(arrData);
      
      //  console.log(heightRef.style)
      console.log(arrObj)
       setShowDom(arrObj)
    
    },[])
  return (
    <div>
        {
            showDom.map(item=>{
                return <div key={item.index} className="box1" style={{ height:item.height }} ref={heightRef}>{item.ci_name}</div>
            })
        }
    </div>
  )
}

文章来源:https://blog.csdn.net/weixin_42327537/article/details/135005505
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。