How to get the width of a react element

前端 未结 8 1225
灰色年华
灰色年华 2020-12-01 01:10

Im trying to create a range input that displays a tooltip right above the slider thumb.

I went through some vanilla JS examples online and it seems that I need to ha

8条回答
  •  忘掉有多难
    2020-12-01 01:57

    A good practice is listening for resize events to prevent resize on render or even a user window resize that can bug your application.

    const MyComponent = ()=> {
      const myRef = useRef(null)
    
      const [myComponenetWidth, setMyComponentWidth] = useState('')
    
      const handleResize = ()=>{ 
        setMyComponentWidth(myRef.current.offsetWidth)
      }
    
      useEffect(() =>{
        if(myRef.current)
          myRef.current.addEventListener('resize', handleResize)
    
        return ()=> {
         myRef.current.removeEventListener('resize', handleResize)
        }
      }, [myRef])
    
      return (
      
    Hello
    ) }

提交回复
热议问题