"在 React 中,可以使用 `ref` 属性来获取组件的 DOM 元素,并通过 DOM 元素的 `offsetWidth` 和 `offsetHeight` 属性来获取组件的宽度和高度。\n\n下面是一个示例:\n\n`jsx\nimport React, { useRef, useEffect } from 'react';\n\nfunction MyComponent() {\n const componentRef = useRef(null);\n\n useEffect(() => {\n if (componentRef.current) {\n const width = componentRef.current.offsetWidth;\n const height = componentRef.current.offsetHeight;\n console.log('Width:', width);\n console.log('Height:', height);\n }\n }, []);\n\n return

My Component
;\n}\n`\n\n在上述示例中,我们创建了一个名为 `componentRef` 的引用,并将其赋值给组件的 DOM 元素。然后,我们使用 `useEffect` 钩子来确保在组件挂载后才获取元素的宽度和高度。在 `useEffect` 的回调函数中,我们可以通过 `componentRef.current.offsetWidth` 和 `componentRef.current.offsetHeight` 来获取组件的宽度和高度,并将其打印到控制台中。\n\n请注意,在函数组件中使用 `ref` 时,需要使用 `useRef` 创建引用,并且要确保在使用引用之前,组件已经被挂载到 DOM 中。"

ReactJS 获取组件宽度和高度 - 使用 Ref 和 useEffect

原文地址: https://www.cveoy.top/t/topic/p0Ny 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录