react移动端适配

一、自定义方法配置

1.使用JavaScript动态设置根元素的字体大小: 为了实现响应式的自适应效果,可以结合JavaScript根据屏幕大小动态设置根元素的字体大小。可以使用window.innerWidth获取窗口的宽度,然后根据需要的适配方案计算并设置根元素的字体大小。可在index.html中添加中:

function setRootFontSize() {
  var screenWidth = window.innerWidth;
  // 根据屏幕宽度计算并设置根元素的字体大小
  var rootFontSize = screenWidth / 100; // 例如,每100个像素为1rem,可以根据需要进行调整
  document.documentElement.style.fontSize = rootFontSize + 'px';
}
​
// 在窗口大小改变时调用设置根元素字体大小的函数
window.addEventListener('resize', setRootFontSize);
​
// 页面加载完成后初始化设置根元素字体大小
window.addEventListener('DOMContentLoaded', setRootFontSize);

2.创建rem.js文件,在函数内部,设置了一个基准大小baseSize,表示在375px设计图下使用的默认字体大小。这个值可以根据实际需求进行调整

获取当前窗口的宽度和高度,并进行相应的计算,以适应不同的屏幕尺寸。在非正常屏幕尺寸下,根据宽度与375的比例重新计算屏幕宽度

最后,根据计算得到的窗口宽度和基准比例,计算出对应的rem值,并将其应用于根元素的字体大小,即修改document.documentElement.style.fontSize的值

// 设置 rem 函数
function setRem () {
  //  PC端
  console.log('非移动设备')
  // 基准大小
  baseSize = 16;
  let baseApp = baseSize / 750; // 表示750的设计图,使用100PX的默认值
  let windowWidth = window.innerWidth; // 当前窗口的宽度
  let windowHeight = window.innerHeight; // 当前窗口的高度
​
  // 非正常屏幕下的尺寸换算
  let dueH = windowWidth / 375
  
  if (windowHeight < dueH) { // 当前屏幕高度小于应有的屏幕高度,就需要根据当前屏幕高度重新计算屏幕宽度
    windowWidth = windowHeight /667
  }
​
  let rem = windowWidth * baseApp; // 以默认比例值乘以当前窗口宽度,得到该宽度下的相应font-size值
  document.documentElement.style.fontSize =  rem + "px";//利用DOM去修改值
}
​
// 页面加载完成后初始化设置根元素字体大小、初始化
window.addEventListener('DOMContentLoaded', setRem);
​
// 在窗口大小改变时调用设置根元素字体大小的函数
window.addEventListener('resize', setRem);

二、使用lib-flexible postcss-pxtorem插件

1.安包

npm
npm install lib-flexible postcss-pxtorem

yarn
yarn add lib-flexible postcss-pxtorem

针对react-create-app创建的项目,webpeck默认隐藏,有两种方式引入插件:

方式一:解包,在webpack中修改

1. 解包

yarn eject
npm run eject
解包完成后,进入 config 文件夹,打开 config/webpack.config.js,搜索 postcss-loader
替换 options : {} 对象

rootValue:设计图尺寸修改

options: {
          postcssOptions: {
            // Necessary for external CSS imports to work
            // https://github.com/facebook/create-react-app/issues/2677
            ident: "postcss",
            config: false,
            plugins: !useTailwind
              ? [
                  "postcss-flexbugs-fixes",
                  [
                    "postcss-preset-env",
                    {
                      autoprefixer: {
                        flexbox: "no-2009",
                      },
                      stage: 3,
                    },
                  ],
                  [
                    "postcss-pxtorem",
                    {
                      rootValue: 75, //设计图最大宽度除以10  //比如750的宽就写成75  我这边是1125的宽
                      selectorBlackList: [],
                      propList: ["*"],
                      exclude: /node_modules/i,
                    },
                  ],
                  // Adds PostCSS Normalize as the reset css with default options,
                  // so that it honors browserslist config in package.json
                  // which in turn let's users customize the target behavior as per their needs.
                  "postcss-normalize",
                ]
              : [
                  "tailwindcss",
                  "postcss-flexbugs-fixes",
                  [
                    "postcss-preset-env",
                    {
                      autoprefixer: {
                        flexbox: "no-2009",
                      },
                      stage: 3,
                    },
                  ],
                  [
                    "postcss-pxtorem",
                    {
                      rootValue: 75, //设计图最大宽度除以10  //比如750的宽就写成75  我这边是1125的宽
                      selectorBlackList: [],
                      propList: ["*"],
                      exclude: /node_modules/i,
                    },
                  ],
                ],
          },
          sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
        },

 2.引入flexible

在index.js中引入,引入完成重新启动项目即可见效果

import 'lib-flexible'

方式二:配置craco, @craco/craco: 使项目不需要 eject暴露配置就可以修改webpack配置

ps: 根据设计稿大小尺寸来修改rootValue的值即可 

const CracoLessPlugin = require('craco-less');
 
module.exports = {
    // 配置less,让工程可以编译less
    plugins: [
        {
            plugin: CracoLessPlugin,
            options: {
                lessLoaderOptions: {
                    lessOptions: {
                        javascriptEnabled: true,
                    },
                },
            },
        },
    ],
   // 配置rem适配
    style: {
        postcss: {
            mode: 'extends',
            loaderOptions: {
                postcssOptions: {
                    ident: 'postcss',
                    plugins: [
                        [
                            'postcss-pxtorem',
                            {
                                rootValue: 375/10, // 根元素字体大小
                                // propList: ['width', 'height']
                                propList: ['*']
                            },
                        ],
                    ],
                },
            },
        },
    },
};

在index.js顶部引入 lib-flexible,下图是index.js的全部代码,重启项目后即可生效

import React from 'react';
import ReactDOM from 'react-dom';
import 'lib-flexible'
import App from './App';
 
 
ReactDOM.render(
        <App />,
  document.getElementById('root')

)

ps:less 样式文件中还是按照px写的,到页面上会自动适配转为rem

.demo {
  color: white;
  background-color: black;
  width: 375px;
  height: 50px;
  margin: 0 auto;
  margin-top: 15px;
  text-align: center;
}
import React, {Component} from 'react';
import './login.less'
 
class Login extends Component {
    render() {
        return (
            <div className={"demo"}>
            </div>
        );
    }
}
 
export default Login;

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值