react怎么获取dom元素的宽度和高度

avatar
作者
筋斗云
阅读量:2

在React中,可以使用ref来获取DOM元素的宽度和高度。

首先,在组件中创建一个ref对象,然后将它传递给要获取宽度和高度的DOM元素:

class MyComponent extends React.Component {   constructor(props) {     super(props);     this.myRef = React.createRef();   }    componentDidMount() {     const element = this.myRef.current;     const width = element.offsetWidth;     const height = element.offsetHeight;     console.log('Width:', width);     console.log('Height:', height);   }    render() {     return <div ref={this.myRef}>Hello, World!</div>;   } } 

在componentDidMount生命周期方法中,可以使用ref.current来获取DOM元素的引用。然后,可以使用offsetWidth和offsetHeight属性来获取宽度和高度。

请注意,要确保在组件渲染后才能获取DOM元素的宽度和高度,因此将获取宽度和高度的代码放在componentDidMount生命周期方法中。

另外,也可以使用其他生命周期方法,如componentDidUpdate,来获取DOM元素的宽度和高度。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!