在 React 中使用 Ref 获取元素的宽度
Get the Width of an Element using a Ref in React
在 React 中使用 ref 获取元素的宽度:
ref
在元素上设置道具。- 在
useLayoutEffect
挂钩中,更新宽度的状态变量。 - 使用该
offsetWidth
属性获取元素的宽度。
import {useLayoutEffect, useRef, useState} from 'react'; export default function App() { const ref = useRef(null); const [width, setWidth] = useState(0); const [height, setHeight] = useState(0); useLayoutEffect(() => { setWidth(ref.current.offsetWidth); setHeight(ref.current.offsetHeight); }, []); return ( <div ref={ref}> <h2>Width: {width}</h2> <h2>Height: {height}</h2> </div> ); }
useRef ()钩子可以传递一个初始值作为参数。该钩子返回一个可变的 ref 对象,其.current
属性被初始化为传递的参数。
current
property on the ref object to get access to the div
element on which we set the ref
prop.When we pass a ref prop to an element, e.g. <div ref={myRef} />
, React sets
the .current
property of the ref object to the corresponding DOM node.
We passed an empty dependencies array to the
useLayoutEffect
hook, so it’s only going to run when the component mounts.
useLayoutEffect(() => { setWidth(ref.current.offsetWidth); setHeight(ref.current.offsetHeight); }, []);
The useLayoutEffect
hook is identical to useEffect
, but fires synchronously
after all DOM mutations.
The useLayoutEffect
hook is often used to read layout from the DOM.
We used the useLayoutEffect
hook because we need to wait for the ref
to be
set on the element and for the element to get rendered before accessing its
offsetHeight
and offsetWidth
properties.
The
offsetWidth
property returns the width of the element in pixels, including any borders,
padding and vertical scrollbars (if present).
The
offsetHeight
property returns the height of the element in pixels, including vertical padding
and borders.
Alternatively, you can use the
clientWidth
property, which returns the width of the element in pixels, including padding
but excluding borders, margins and vertical scrollbars (if present).
useLayoutEffect(() => { setWidth(ref.current.clientWidth); setHeight(ref.current.clientHeight); }, []);