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

0、前言

                        仿照   vue2-scale-box

1、调用示例

    <ScreenAutoBox width={1920} height={1080} flat={true}>
       {/* xxx代码 */}
    </ScreenAutoBox>

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<HTMLDivElement> = 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 (
    <div ref={BoxRef} style={
  { ...style, transform: transformValue }}>
      {children}
    </div>
  )
}

相关推荐

  1. VUE可适化适应

    2024-02-03 21:00:02       33 阅读
  2. vue3 可视化适应屏幕组件

    2024-02-03 21:00:02       49 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-03 21:00:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-03 21:00:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-03 21:00:02       82 阅读
  4. Python语言-面向对象

    2024-02-03 21:00:02       91 阅读

热门阅读

  1. muduo库的模拟实现——Reactor部分

    2024-02-03 21:00:02       49 阅读
  2. 2402d,d变量2

    2024-02-03 21:00:02       55 阅读
  3. 个人建站前端篇(四)ssr项目路由

    2024-02-03 21:00:02       51 阅读
  4. 互联网摸鱼日报(2024-02-02)

    2024-02-03 21:00:02       52 阅读
  5. C#解决在Winform中绘图异常闪烁问题

    2024-02-03 21:00:02       45 阅读
  6. 1291. Sequential Digits

    2024-02-03 21:00:02       54 阅读
  7. 【前端】弹框组件

    2024-02-03 21:00:02       50 阅读
  8. MYSQL函数

    2024-02-03 21:00:02       43 阅读
  9. Elastic Search

    2024-02-03 21:00:02       56 阅读
  10. 开源软件的影响力

    2024-02-03 21:00:02       49 阅读
  11. 【MySQL】MySQL 查询两个日期内的每一天

    2024-02-03 21:00:02       48 阅读
  12. 在nodejs中使用mysql2

    2024-02-03 21:00:02       48 阅读
  13. themeleaf:入门(一)

    2024-02-03 21:00:02       44 阅读