react移动端屏幕设配

430 阅读2分钟

React移动端响应式布局开发

<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">

引入reset.min.css 清除默认样式

实现REM响应式布局开发的步骤

  1. 找参照的比例 (例如,设计稿的比例->一般都是750px),在这个比例下,给予html.fontSize一个初始值
html{
    font-size:100px;
    //750px的设计稿中,1rem=100px
    //未来我们需要把从设计稿中测量出来的尺寸(px单位)转换为REM单位设置样式
}
  1. 我们需要根据当前设备的宽度,计算相对设计稿750来讲,缩放比例,也跟着缩放【rem和px的换算比例一改,则所有之前的rem单位的样式也会跟着缩放】---需要使用js实现
计算当前设备下,Rem和px的换算比例
(function (){
    const computed=()=>{
         let html=document.documentElement,deviceW=html.clientWidth,designW=750;
         //计算公式 750/100 
         //当前宽度*100/750
         let ratio=deviceW*100/750
         html.style.fontSize=ratio+'px'
    };
    computed();
    window.addEventListener('resize',computed)
})()

3.给页面设置最大宽度,超过这个宽度,不再放rem继续放大;内容居中,两边空出来 给root添加最大宽度

#root{
    max-width:750px;
    margin:0 auto;
    }
    
(function (){
    const computed=()=>{
         let html=document.documentElement,deviceW=html.clientWidth,designW=750;
        //判断有没有超过最大宽度
         if(deviceW>designW){
             html.style.fontSize='100px'
             return;
         }
         //计算公式 750/100 
         //当前宽度*100/750
             let ratio=deviceW*10sSSSSSSSs0/750sSSSSS
         html.style.fontSize=ratio+'px'
    };
    computed();
    window.addEventListener('resize',computed)
})()    

4.配置好rem响应式布局&&样式处理

lib-flexible 设置rem和px换算比例的,+根据设备宽度的变化自动计算 +html.style.fontSize=设备宽度/10+‘px’ +750设计稿中 1rem=75px +375设备上 1rem=37.5px

postcss-pxtorem可以帮我们把写的px,按照当时的换算比例,自动转换为rem不需要自己算

webpack中配置

image.png

const px2rem=require('postcss-pxtorem);
px2rem({
//基于lib-flexible,750设计稿,就会设置1REM=75PX,此时webpack编译的时候,我们也需要让px2rem插件,按照1rem=75px,把我们测出来德尔并且编写的px样式,自动转换为REM
    rootValue:75,
    //对所有样式文件都生效
    propList:['*']
})

postcss

在入口中,我们导入lib-flexible,确保在不同的设备上,可以等比例的对rem的换算比例进行缩放 手动设置:设备宽度超过750px后,不再继续放大

index.js

import 'lib-flexible'

// 处理最大宽度
(function(){
    const handleMax=function handleMax(){
        let html=document.documentElement,root=document.getElementById("root"),size=parseFloat(html.style.fontSize);
        root.style.maxWidth="750px";
        
        if(size>=750){
            html.style.fontSize='75px'
        }
    };
    handleMax();
    window.addEventListener('resize',handleMax)
})()