reactでDOM要素の幅と高さを取得する方法は何ですか?

Reactでは、DOM要素の幅や高さを取得するためにrefを使用することができます。

最初に、コンポーネント内で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ライフサイクルメソッド内に配置することを確認してください。

その他にも、DOM要素の幅や高さを取得するためにcomponentDidUpdateなどのライフサイクルメソッドを使用することもできます。

bannerAds