React 自适应屏幕App记录,可用于数据大屏框架

使用css3 transform 实现指定盒子的等比放大/缩写,通过js监听窗口变动事件更新计算缩放比例,从而达到自适应屏幕的目的

上代码:

import React from "react";
import Route from "@/route";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      center: {
        margin: 0,
        height: "100vh",
        overflow:"hidden"
      },
      body: {
        width: "1920px",
        height: "1080px",
      },
    };
  }
  adaptation = () => {
    console.log("adaptation!!");
    const w = document.documentElement.clientWidth;
    const h = document.documentElement.clientHeight;
    const l = 1920 / 1080;
    const width = h * l;
    const margin = (w - width) / 2 < 0 ? 0 : (w - width) / 2;
    const scale = h / 1080;

    this.setState(() => ({
      center: {
        margin: `0 ${margin}px`,
        height: "100vh",
        overflow:"hidden"
      },
      body: {
        transform: `scale(${scale}, ${scale})`,
        width: "1920px",
        height: "1080px",
        transformOrigin: "0 0",
        transition: "all 0.3s linear",
      },
    }));
  };
  componentDidMount() {
    this.adaptation();
    window.addEventListener("resize", this.adaptation);
  }

  render() {
    return (
      <div style={this.state.center}>
        <div style={this.state.body}>
          <Route></Route>
        </div>
      </div>
    );
  }
}

export default App;