react中封装组件对三方库或者已有ui组件进行自动调整大小嵌入显示区域

原因:有些三方库的组件或者已有的组件ui部分无法调整大小,比如组件是全屏覆盖显示但是在新开发的迭代要求缩小到部分区域显示

解决方法:使用css的属性transform scale,通过绝对定位处理放大或者缩小的处理区域

ini 复制代码
import React, {
  FC, useEffect, useRef, useState,
} from 'react';
import { useSize } from 'ahooks';
import { isEmpty, min } from 'lodash';
import { css } from '@emotion/css';

interface Props {
  debug?: boolean
  lockMaxWidth?: boolean
  lockMaxHeight?: boolean
}

export const AutoScale: FC<React.PropsWithChildren & Props> = ({ children, debug, lockMaxHeight = true, lockMaxWidth = true }) => {
  const outsideWrapperRef = useRef<HTMLDivElement>(null);
  const insideWrapperRef = useRef<HTMLDivElement>(null);
  const outsideSize = useSize(outsideWrapperRef.current?.parentElement);
  const insideSize = useSize(insideWrapperRef);
  const [scale, setScale] = useState(1);
  const [height, setHeight] = useState(0);
  const [width, setWidth] = useState(0);

  useEffect(() => {
    if (isEmpty(insideSize) || isEmpty(outsideSize)) {
      return;
    }
    if (debug) {
      console.log(outsideSize);
    }

    const scaleWidth = outsideSize.width / insideSize.width;
    const scaleHeight = outsideSize.height / insideSize.height;
    let resultScale;

    switch (true) {
      case lockMaxWidth && !lockMaxHeight:
        resultScale = scaleWidth;
        break;
      case !lockMaxWidth && lockMaxHeight:
        resultScale = scaleHeight;
        break;
      case lockMaxWidth && lockMaxHeight:
        resultScale = min([scaleWidth, scaleHeight]);
        break;
      default:
        resultScale = scaleWidth;
        break;
    }

    setScale(resultScale);
    setHeight(insideSize.height * resultScale);
    setWidth(insideSize.width * resultScale);
  }, [insideSize, outsideSize]);

  return (
    <div
      ref={outsideWrapperRef}
      className={css`
          position: relative;
          width: ${`${width}px` || '100%'};
          height: ${`${height}px` || '100%'};
          overflow: ${width ? 'initial' : 'hidden'};
      `}
    >
      <div
        ref={insideWrapperRef}
        className={css`
          position: absolute;
          top: 0;
          left: 0;
          transform-origin: left top;
          transform: scale(${scale});
      `}
      >
        {children}
      </div>
    </div>
  );
};
相关推荐
emojiwoo8 小时前
【前端基础知识系列六】React 项目基本框架及常见文件夹作用总结(图文版)
前端·react.js·前端框架
Bug改不动了10 小时前
React Native 与 UniApp 对比
react native·react.js·uni-app
然我11 小时前
React 16.8:不止 Hooks 那么简单,这才是真正的划时代更新 🚀
前端·react.js·前端框架
OEC小胖胖11 小时前
【React Hooks】封装的艺术:如何编写高质量的 React 自-定义 Hooks
前端·react.js·前端框架·web
404_Not_Found1112 小时前
用 react + ts 实现我的第一个 todoList
react.js
木春14 小时前
React入门:构建你的第一个应用
前端·react.js
吃奥特曼的饼干17 小时前
React useEffect 清理函数:别让依赖数组坑了你!
前端·react.js
随笔记17 小时前
react中函数式组件和类组件有什么区别?新建的react项目用函数式组件还是类组件?
前端·react.js·typescript
emojiwoo17 小时前
React 状态管理:useState 与 useDatePersistentState 深度对比
前端·javascript·react.js
D11_17 小时前
【React】JSX基础
前端·react.js·前端框架