要作移動端應用,同時要適配ios、android和微信。搜索、試驗、思考...幾天內進行了好幾輪,最終決定採用react-native & antd-mobile來實現咱們的目的。node
在網上搜索,看到了多種方案。第一種,利用redux,共享業務邏輯,本身維護兩套UI組件;第二種,利用react-native-web,先寫移動端,再將移動端轉換成H5;第三種:利用styled-components來封裝UI組件,也要維護兩套UI;第四種:利用antd-mobile來適配三端。
最終決定選擇antd-mobile方式,由於其自己就是一套很好的解決方案,文檔較全,實現方式簡單,雖然是兩套代碼,但現有組件已經不少,也容易擴展。我已經修復了一個小bug,自行發佈到了npm,並替換到項目中,這樣可以快速方便的實現本身想要的組件。react
全部的界面元素都使用antd-mobile的組件來實現,不夠用的,不符合要求的,直接改動antd-mobile。android
antd-mobile要支持H5,在要webpack中進行配置,打包web版的代碼。webpack
import antd-mobileios
{ test: /\.(js|jsx)$/, exclude: /node_modules/, use: [{ loader:'babel-loader', options:{ presets: ['es2015', "stage-2", 'react'], plugins: [ ["transform-runtime"],["import", {libraryName: "antdm", style: true}] ], } }], },
resolve web.*git
resolve: { mainFiles: ["index.web","index"],// 這裏哦 modules: ['app', 'node_modules', path.join(__dirname, '../node_modules')], extensions: [ '.web.tsx', '.web.ts', '.web.jsx', '.web.js', '.ts', '.tsx', '.js', '.jsx', '.react.js', ], mainFields: [ 'browser', 'jsnext:main', 'main', ], },
antd-mobile文檔中只提了複雜的組件,但咱們在H5中常常用的div與native中的View應該如何處理呢?看文檔、搜索,都沒有找到我想要的方法;在github中看別人家的代碼,發現都是直接用了div或native的View,不能同時適配三端。以致於我一度想引入styled-components來封裝,但總以爲引入styled-components只用來處理幾個基本元素,不划算。最後是想起來要看看antd-mobile的源碼,在antd-mobile中來作引入styled-components作的事,不就能夠了嗎!結果發現antd-mobile已經有封裝了,就是View。github
問題基本解決了,但運行時會有以下的警告信息:web
Warning: Unknown prop `Component` on <div> tag. Remove this prop from the element. For details, see https://fb.me/react-unknown-prop in div (created by View) in View (at Root.js:15) in Provider (at Root.js:14) in Root (at index.js:20) in AppContainer (at index.js:19)
看源代碼,是有個小bug,順手修改了,編譯,運行,問題解決。提交pull requests,人家不可能很快的更新,並且可能有的改動只是爲了適應咱們本身的項目,所以發佈到npm中,名字叫antdm。npm
入口文件會有三個,原則是儘可能保持簡單redux
ios:index.ios.js
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import Root from './src/containers/Root'; import configureStore from './src/store/configureStore.js'; const store = configureStore(); class T3 extends Component { render() { return ( <Root store={store}/> ); } } AppRegistry.registerComponent('t3', () => T3);
web:/src/web/index.js
import React from 'react'; import { render } from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import Root from '../containers/Root'; import configureStore from '../store/configureStore'; const store = configureStore(); render( <AppContainer> <Root store={store} /> </AppContainer>, document.getElementById('root') )
android:index.android.js
還未編寫,應該與ios差很少。
https://git.oschina.net/zhoutk/t3.git https://github.com/zhoutk/t3.git
git clone https://git.oschina.net/zhoutk/t3.git or git clone https://github.com/zhoutk/t3.git cd t3 npm i ios: npm run ios web: npm run web
利用react-native和antd-mobie基本達到移動端適配三端的要求,但在作項目的同時,可能須要基於antd-mobile逐步創建起一套適合本身的UI組件。謝謝阿里的兄弟們!