react手机机端css_react 配置 rem(px转rem适配手机端)

1、 计算 js

在index.html中添加以下js

!(function(win, doc) {

function setFontSize() {

var baseFontSize = 100;

var baseWidth = 320;

var clientWidth = document.documentElement.clientWidth || window.innerWidth;

var innerWidth = Math.max(Math.min(clientWidth, 480), 320);

var rem = 100;

if (innerWidth > 362 && innerWidth <= 375) {

rem = Math.floor(innerWidth / baseWidth * baseFontSize * 0.9);

}

if (innerWidth > 375) {

rem = Math.floor(innerWidth / baseWidth * baseFontSize * 0.84);

}

window.__baseREM = rem;

document.querySelector('html').style.fontSize = rem + 'px';

}

var evt = 'onorientationchange' in win ? 'orientationchange' : 'resize';

var timer = null;

win.addEventListener(evt, function() {

clearTimeout(timer);

timer = setTimeout(setFontSize, 300);

}, false);

win.addEventListener("pageshow", function(e) {

if (e.persisted) {

clearTimeout(timer);

timer = setTimeout(setFontSize, 300);

}

}, false);

setFontSize();

}(window, document));

2、配置webpack.config.js

由于react默认隐藏webpack配置需要手动显示。首先执行命令显示webpack配置

npm run eject

//Are you sure you want to eject? This action is permanent. (y/N)

y

安装以下包:lib-flexible sass-loader node-sass postcss-px2rem-exclude

npm i lib-flexible sass-loader node-sass postcss-px2rem-exclude --save

修改webpack.config.js ,首先引入:

const px2rem = require('postcss-px2rem-exclude');

//加入

px2rem({remUnit:75,exclude: /node_modules/i})

然后找到处理postcss-loader的地方:

image.png

在我们的入口文件index.js 中引入lib-flexible

import "lib-flexible"

最后一步修改index.html

你可能感兴趣的:(react手机机端css)