[react-vw-layout] 移動端h5最新vw適配方案搭配react + react router 4


最近在react 上配置使用vw 適配方案,總體表現(xiàn)優(yōu)秀寓盗。所以很多同學們都在觀望vw 適配到底行不行灌砖,靠不靠譜。

在這里傀蚌,從我在項目中實戰(zhàn)應用下來但經(jīng)驗來說基显,可行,靠譜善炫!

簡單配置撩幽,一勞永逸,高可靠的還原設計師的稿子箩艺,給你底氣和設計師對標UI窜醉。

歡迎挑戰(zhàn)還原度,從此做一個自信的前端工程師艺谆。哈哈~

一定要看到底榨惰,可能有你會遇到坑的解藥!拿走不謝++++ 給個小星星吧

https://github.com/caoxiaoke/react-vw-layout


該demo 為vw 適配方案 react 16 && react-router-dom 4+ 搭配使用静汤,一個多頁面路由項目.


步驟:

1读串、創(chuàng)建項目 && 初始化

create-react-app react-vw-layout

cd react-vw-layout

2、開啟我們的配置之路&&簡單配置

react 把配置都隱藏了撒妈,需要我們手動來顯示配置

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

之后可以看到 config文件 && scripts 文件夾

image

3恢暖、安裝我們需要配置用到的插件(建議使用cnpm)

 npm install --save postcss-aspect-ratio-mini postcss-px-to-viewport postcss-write-svg postcss-cssnext postcss-viewport-units cssnano

4、開始配置

在config/webpack.config.js 中修改代碼

先引入postcss cssnano插件

const postcssAspectRatioMini = require('postcss-aspect-ratio-mini');
const postcssPxToViewport = require('postcss-px-to-viewport');
const postcssWriteSvg = require('postcss-write-svg');
const postcssCssnext = require('postcss-cssnext');
const postcssViewportUnits = require('postcss-viewport-units');
const cssnano = require('cssnano');

增加postcss 配置

{
        // Options for PostCSS as we reference these options twice
        // Adds vendor prefixing based on your specified browser support in
        // package.json
        loader: require.resolve('postcss-loader'),
        options: {
          // Necessary for external CSS imports to work
          // https://github.com/facebook/create-react-app/issues/2677
          ident: 'postcss',
          plugins: () => [
            require('postcss-flexbugs-fixes'),
            require('postcss-preset-env')({
              autoprefixer: {
                flexbox: 'no-2009',
              },
              stage: 3,
            }),
            //在這個位置加入我們需要配置的代碼
            //在這個位置加入我們需要配置的代碼
            //在這個位置加入我們需要配置的代碼
            postcssAspectRatioMini({}),
            postcssPxToViewport({
                viewportWidth: 750, // (Number) The width of the viewport.
                viewportHeight: 1334, // (Number) The height of the viewport.
                unitPrecision: 3, // (Number) The decimal numbers to allow the REM units to grow to.
                viewportUnit: 'vw', // (String) Expected units.
                selectorBlackList: ['.ignore', '.hairlines', '.list-row-bottom-line', '.list-row-top-line'], // (Array) The selectors to ignore and leave as px.
                minPixelValue: 1, // (Number) Set the minimum pixel value to replace.
                mediaQuery: false // (Boolean) Allow px to be converted in media queries.
            }),
            postcssWriteSvg({
                utf8: false
            }),
            postcssPresetEnv({}),
            // postcssViewportUnits({
            //  filterRule: rule => rule.selector.indexOf('::after') === -1 && rule.selector.indexOf('::before') === -1 && rule.selector.indexOf(':after') === -1 && rule.selector.indexOf(':before') === -1
            // }),
            postcssViewportUnits({}),
            cssnano({
                "cssnano-preset-advanced": {
                    zindex: false,
                    autoprefixer: false
                },
            })
            //在這個位置加入我們需要配置的代碼
            //在這個位置加入我們需要配置的代碼
            //在這個位置加入我們需要配置的代碼
          ],
          sourceMap: isEnvProduction && shouldUseSourceMap,
        },
      }

5狰右、配置完成以后杰捂,我們可以看到vw 神奇的效果了

 npm run start

瀏覽器會打開 http://localhost:8080/

.App {
    background-color: bisque;
    display: flex;
    color: white;
    justify-content: center;
    align-items: center;
    font-size: 30px;
    height: 200px;
    width: 750px;
}
image

6、我們加入兼容我們android 低版本的機型hack 加入viewport-units-buggyfill配置

同學們棋蚌,經(jīng)過實戰(zhàn)配置viewport-units-buggyfill之后嫁佳,4.2 4.3 4.4+ 系統(tǒng)版本上表現(xiàn)都 ok,項目中主要使用flexbox 布局

demo 版本中直接引入阿里的cdn 文件,在自己項目中可以放自己公司的服務器或者項目中谷暮。

打開public/index.html蒿往,在head 中插入 viewport-units-buggyfill 和body 中使用

<head>
    <script src="http://g.alicdn.com/fdilab/lib3rd/viewport-units-buggyfill/0.6.2/??viewport-units-buggyfill.hacks.min.js,viewport-units-buggyfill.min.js"></script>
</head>

<body>
<script>
    window.onload = function () {
        window.viewportUnitsBuggyfill.init({
            hacks: window.viewportUnitsBuggyfillHacks
        });
    }
</script>
<body>

最后完整的index.html

<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,shrink-to-fit=no"/> <meta name="theme-color" content="#000000" /> <!-- manifest.json provides metadata used when your web app is installed on a user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <!-- Notice the use of %PUBLIC_URL% in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> <title>react-vw-layout</title> <!--<script type="text/javascript" src="/zx_local_res/jssdk/zx.js"></script>--> <script src="http://g.alicdn.com/fdilab/lib3rd/viewport-units-buggyfill/0.6.2/??viewport-units-buggyfill.hacks.min.js,viewport-units-buggyfill.min.js"></script> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <!-- This HTML file is a template. If you open it directly in the browser, you will see an empty page. You can add webfonts, meta tags, or analytics to this file. The build step will place the bundled scripts into the <body> tag. To begin the development, run `npm start` or `yarn start`. To create a production bundle, use `npm run build` or `yarn build`. --> <script> window.onload = function () { window.viewportUnitsBuggyfill.init({ hacks: window.viewportUnitsBuggyfillHacks }); } </script> </body></html>

項目中有遇到的坑:

1、cssnano 如果你的版本為:4+ 以上湿弦,請在配置中如下方案配置:

cssnano({
    "cssnano-preset-advanced": {
        zindex: false,
        autoprefixer: false
    },
})

我遇到了始終把你定位的z-index值重新計算為:1瓤漏,巨坑,不然你會一口老血噴出來的。
和cssnano 3+版本配置不一樣蔬充。


2蝶俱、ios 系統(tǒng)下img不顯示問題,解決方案如下:

/*兼容ios不顯示圖片問題*/
img {
    content: normal !important
}

3饥漫、1px 問題榨呆,解決方案

/*1px 解決方案*/

@svg square {
    @rect {
        fill: var(--color, white);
        width: 100%;
        height: 50%;
    }
}

.example-line {
    width: 100%;
    background: white svg(square param(--color #E6E6E6));
    background-size: 100% 1px;
    background-repeat: no-repeat;
    background-position: bottom left;
}

/*1px 解決方案*/

/*偽元素1px*/

.row-cell:before {
    content: " ";
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    height: 1px;
    border-top: 1px solid #e5e5e5;
    color: #e5e5e5;
    transform-origin: 0 0;
    transform: scaleY(0.5);
    z-index: 2;
}

如果你不使用react 也不使用vue ,在項目中只使用html頁面 vw實現(xiàn)移動端適配庸队,請點這 《如何在html項目中使用vw實現(xiàn)移動端適配》

image
image
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末积蜻,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子彻消,更是在濱河造成了極大的恐慌竿拆,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,185評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件证膨,死亡現(xiàn)場離奇詭異如输,居然都是意外死亡鼓黔,警方通過查閱死者的電腦和手機央勒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,652評論 3 393
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來澳化,“玉大人崔步,你說我怎么就攤上這事《泄龋” “怎么了井濒?”我有些...
    開封第一講書人閱讀 163,524評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長列林。 經(jīng)常有香客問我瑞你,道長,這世上最難降的妖魔是什么希痴? 我笑而不...
    開封第一講書人閱讀 58,339評論 1 293
  • 正文 為了忘掉前任者甲,我火速辦了婚禮,結(jié)果婚禮上砌创,老公的妹妹穿的比我還像新娘虏缸。我一直安慰自己,他們只是感情好嫩实,可當我...
    茶點故事閱讀 67,387評論 6 391
  • 文/花漫 我一把揭開白布刽辙。 她就那樣靜靜地躺著,像睡著了一般甲献。 火紅的嫁衣襯著肌膚如雪宰缤。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,287評論 1 301
  • 那天,我揣著相機與錄音撵溃,去河邊找鬼疚鲤。 笑死,一個胖子當著我的面吹牛缘挑,可吹牛的內(nèi)容都是我干的集歇。 我是一名探鬼主播,決...
    沈念sama閱讀 40,130評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼语淘,長吁一口氣:“原來是場噩夢啊……” “哼诲宇!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起惶翻,我...
    開封第一講書人閱讀 38,985評論 0 275
  • 序言:老撾萬榮一對情侶失蹤姑蓝,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后吕粗,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體纺荧,經(jīng)...
    沈念sama閱讀 45,420評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,617評論 3 334
  • 正文 我和宋清朗相戀三年颅筋,在試婚紗的時候發(fā)現(xiàn)自己被綠了宙暇。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,779評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡议泵,死狀恐怖占贫,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情先口,我是刑警寧澤型奥,帶...
    沈念sama閱讀 35,477評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站碉京,受9級特大地震影響厢汹,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜谐宙,卻給世界環(huán)境...
    茶點故事閱讀 41,088評論 3 328
  • 文/蒙蒙 一烫葬、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧卧惜,春花似錦厘灼、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,716評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至茅姜,卻和暖如春闪朱,著一層夾襖步出監(jiān)牢的瞬間月匣,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,857評論 1 269
  • 我被黑心中介騙來泰國打工奋姿, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留锄开,地道東北人。 一個月前我還...
    沈念sama閱讀 47,876評論 2 370
  • 正文 我出身青樓称诗,卻偏偏與公主長得像萍悴,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子寓免,可洞房花燭夜當晚...
    茶點故事閱讀 44,700評論 2 354

推薦閱讀更多精彩內(nèi)容