react 中获取元素宽度

// 子组件 nav.js
import React, { useRef, useEffect, useState, useLayoutEffect } from "react";
import './nav.less'
function Nav({items}) {
    
    const ref = useRef(null);
    useEffect(() => {
        const div = ref.current;
        const { width } = div.getBoundingClientRect();
        console.log('navigationwidth', width)
        const children = [...div.childNodes];
        // all the widths
        const childrenWidths = children.map(child => {
            console.log('child', child.getBoundingClientRect())
            console.log('childWidth', child.getBoundingClientRect().width)
        } )
        // const itemIndex = getLastVisibleItem(ref.current)

        // setLastVisibleMenuItem(itemIndex);
        // console.log('itemIndex', itemIndex)
    }, [ref]);
    useLayoutEffect(() => {
        // do something
      })
    
    return (
        <div className="navigation" ref={ref}>
            {items.map(item => <a key={item.href} href={item.href}>{item.name}</a>)}
        </div>
    )
}

export default Nav

// 父组件 index.js
 import React,{useReducer, useContext} from 'react'
import Nav from './components/nav.js'
function Counter() {
  const navItem = [
      {
        href: '/nav1',
        name: '菜单'
      },
      {
        href: '/nav2',
        name: '菜单2'
      },
      {
        href: '/nav3',
        name: '导航菜单3'
      },
      {
        href: '/nav4',
        name: '地图菜单导航'
      },
    ]
  <>
    <Nav items ={navItem}></Nav>
  </>
}

 

posted @ 2023-10-25 14:18  Webwhl  阅读(321)  评论(0编辑  收藏  举报