React中封装大屏自适应(拉伸)仿照 vue2-scale-box

0、前言

                        仿照   vue2-scale-box

1、调用示例

    
       {/* xxx代码 */}
    

2、组件代码

import { CSSProperties, ReactNode, RefObject, useEffect, useRef, useState } from 'react'

//数据大屏自适应函数
const getTransform = (designWidth = 1920, designHeight = 1080, flat = true) => {
  const w = document.documentElement.clientWidth
  const h = document.documentElement.clientHeight
  if (flat) {
    //缩放比例(拉伸)
    return `scaleX(${w / designWidth}) scaleY(${h / designHeight}) translate(-50%, -50%)`
  } else {
    // 不拉伸
    return `scale(${w / h > designWidth / designHeight ? h / designHeight : w / designWidth}) translate(-50%, -50%)`
  }
}

export default function ScreenAutoBox({
  width = 1920,
  height = 1080,
  flat = true, // 是否拉伸
  children
}: {
  width?: number
  height?: number
  flat?: boolean
  children?: ReactNode
}) {
  const BoxRef: RefObject = useRef(null)
  const [transformValue, setTransformValue] = useState('scaleX(0) scaleY(0) translate(-50%, -50%)')

  useEffect(() => {
    setTransformValue(getTransform(width, height, flat))
    window.onresize = () => setTransformValue(getTransform(width, height, flat))
    // 销毁监听自适应消失
    return () => {
      window.onresize = null
    }
  }, [])

  const style: CSSProperties = {
    width: width + 'px',
    height: height + 'px',
    position: 'fixed',
    left: '50%',
    top: '50%',
    transformOrigin: '0 0',
    backgroundColor: 'transparent',
    zIndex: 100
  }
  return (
    
{children}
) }

你可能感兴趣的:(react.js,前端,javascript)