• 自适应屏幕react


    想必近几年前端的数据可视化越来越重要了,很多甲方爸爸都喜欢那种炫酷的大屏幕设计,类似如下这种:

    遇到的这样的项目,二话不说,echarts或者antv,再搭配各种mvvm框架(react,vue),找二次封装过的组件,然后开始埋头开始写了,写着写着你会发现,如何适配不同屏幕呢?css媒体查询吧,用vw吧,哪个好点呢。其实写到最后,我觉得都不好

    对于这种拿不定主意的情况呢,最好还是参考大厂的做法,于是去找了网易有数,百度suger等,他们是如何写这样的页面的

    仔细观察他们都采用了css3的缩放transform: scale(X)属性,看到这是不是有种豁然开朗的感觉
    于是我们只要监听浏览器的窗口大小,然后控制变化的比例就好了
    以React的写法为例

    getScale=() => {
        // 固定好16:9的宽高比,计算出最合适的缩放比,宽高比可根据需要自行更改
        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)
    监听window的resize事件最好加个节流函数debounce
    window.addEventListener('resize', this.setScale)

    然后一个简单的组件就封装好了

    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
    .scale-box{
      transform-origin: 0 0;
      position: absolute;
      left: 50%;
      top: 50%;
      transition: 0.3s;
    }
    只要把页面放在这个组件中,就能实现跟大厂们类似的效果。这种方式下不管屏幕有多大,分辨率有多高,只要屏幕的比例跟你定的比例一致,都能呈现出完美效果。而且开发过程中,样式的单位也可以直接用px,省去了转换的烦恼~~~

    链接:https://www.jianshu.com/p/b2fd58d31515
  • 相关阅读:
    Fiddler抓包使用教程-安装配置
    Fiddler抓包使用教程-扫盲篇
    【Python3 爬虫】14_爬取淘宝上的手机图片
    【Python3 爬虫】13_爬取博客园首页所有文章
    【Python3 爬虫】12_代理IP的使用
    【Python】self的用法扫盲
    【Python3 爬虫】11_报错No module named 'requests'
    【Python3 爬虫】10_Beautiful Soup库的使用
    【DB2】国标行业分类存储,通过SQL查询出层级关系
    【Python3 爬虫】09_正则表达式(re.math()、re.search()、re.sub()、全局匹配函数)
  • 原文地址:https://www.cnblogs.com/zhangyezi/p/13186652.html
Copyright © 2020-2023  润新知