获取可缩放元素的宽高

362 阅读1分钟
import * as React from 'react'
import elementResizeDetectorMarker from 'element-resize-detector'
import { debounce } from 'lodash'

class GetResizeWidthHeight extends React.PureComponent {
  constructor (props) {
    super(props)
    this.state = {
      width: 0,
      height:0,
    }
    this.ResizeContainer = React.createRef()
  }
  componentDidMount() {
    const Resize = elementResizeDetectorMarker()
    Resize.listenTo(
      this.ResizeContainer.current,
      debounce(
        element => {
          this.setState({
            width: element.offsetWidth,
            height: element.offsetHeight
          })
        },
        250,
        { leading: true, trailing: true }//不知有何作用
      )
    )
  }
  render() {
    const { width, height } = this.state
    console.log( width, height )
    return (
      <div ref=this.ResizeContainer>
        text
      <div/>
    )
  }