欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

React下获取width和height

程序员文章站 2022-05-04 23:40:43
...

React下获取width和height

利用ref保存DOM节点,然后读取clientWidth,clientHeight获取宽高参数。

import React, { Component } from 'react';
import 'assets/css/App.css'


export class App extends Component {


  constructor(props) {
    super(props);

    this.saveRef = ref => {this.refDom = ref};
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e) {
    const {clientWidth, clientHeight} = this.refDom;
    console.log('====================================');
    console.log(clientWidth, clientHeight, this.refDom);
    console.log('====================================');
  }

  render() {

    return (
      <div ref={this.saveRef} onClick={this.handleClick} > Loading...</div>
    );
  }
}

export default App;