大屏幕可视化

import React, { Component } from 'react';
import debounce from 'lodash.debounce'
import s from './index.less'

class Comp extends Component{
  constructor(p) {
    super(p)
    this.state={
      scale: this.getScale()
    }
  }
  componentDidMount() {
    window.addEventListener('resize', this.setScale)
  }
  getScale=() => {
    const {width=1920, height=1080} = this.props
    let ww=window.innerWidth/width
    let wh=window.innerHeight/height
    return ww<wh?ww: wh
  }
  setScale = debounce(() => {
    let scale=this.getScale()
    this.setState({ scale })
  }, 500)
  render() {
    const {width=1920, height=1080, children} = this.props
    const {scale} = this.state
    return(
      <div
        className={s['scale-box']}
        style={{
          transform: `scale(${scale}) translate(-50%, -50%)`,
          WebkitTransform: `scale(${scale}) translate(-50%, -50%)`,
          width,
          height
        }}
      >
        {children}
      </div>
    )
  }
  componentWillUnmount() {
    window.removeEventListener('resize', this.setScale)
  }
}

export default Comp

原文链接 https://www.jianshu.com/p/b2fd58d31515

最后附上npm链接:https://www.npmjs.com/package/react-scale-box  

posted @ 2021-12-29 15:47  玖捌  阅读(37)  评论(0)    收藏  举报