現(xiàn)有iOS項(xiàng)目中嵌入幾個(gè)React Native頁(yè)面
2016.12.20 15:19 *字?jǐn)?shù)1500閱讀1631評(píng)論5喜歡25
具體步驟參考官方文檔帘饶,環(huán)境弄好后坟桅,工程目錄如下
原的iOS項(xiàng)目被放在了根目錄的iOS的文件夾下(沒(méi)做安卓,所以沒(méi)有安卓的路徑)
React Native的iOS入口是index.ios.js
其他React Native的代碼放在了組件文件夾
main.jsbundle為我們所寫(xiě)的React Native代碼的集合粹胯,發(fā)布時(shí)才生成(或方便真機(jī)調(diào)試)
2.入口
RN入口index.ios.js
'use strict'; //使用嚴(yán)格模式import React, { Component } from 'react';import {AppRegistry,//用于注冊(cè)組件StyleSheet,//使用樣式Text,View,Image,NavigatorIOS,//導(dǎo)航控制器TouchableHighlight,//點(diǎn)擊效果NativeModules//調(diào)用native方法} from 'react-native';import Repayment from './component/repayment';import SettlementAccountList from './component/SettlementAccountList';export default class MECRM extends Component {_handleNavigationBackRequest() {var RNBridge = NativeModules.RNBridge;RNBridge.back();}_settlementAccountList() {var status = this.props["status"];if (status === 0 || status === 3) {this.refs['nav'].push({title: '返款人信息表',component: SettlementAccountList,barTintColor: '#7B9DFD',tintColor: 'white',passProps: {}})}}render() {return ( this._handleNavigationBackRequest(),onRightButtonPress: () => this._settlementAccountList(),passProps: {orderid: this.props["orderid"],status: this.props["status"],price: this.props["price"]},barTintColor: '#7B9DFD'}}style={{flex: 1}}itemWrapperStyle={styles.itemWrapper}tintColor="white"titleTextColor ='white'/>);}}const styles = StyleSheet.create({container: {flex: 1,justifyContent: 'center',alignItems: 'center',backgroundColor: '#F5FCFF',},welcome: {fontSize: 20,textAlign: 'center',margin: 10,},instructions: {textAlign: 'center',color: '#333333',marginBottom: 5,},});AppRegistry.registerComponent('RNBackApply', () => MECRM);
index.ios.js作為RN代碼入口特幔,關(guān)鍵點(diǎn)是NavigatorIOS標(biāo)簽:
ref ='nav'咨演,把NavigatorIOS對(duì)象標(biāo)記為'nav'方便調(diào)用,類(lèi)似iOS開(kāi)發(fā)中的標(biāo)簽蚯斯,this.refs ['nav']便能找到NavigatorIOS對(duì)象(彌補(bǔ)這個(gè)傳遞的麻煩)
initialRoute初始化路由薄风,這里初始化起始頁(yè)為還款,然后點(diǎn)擊左右按鈕分別執(zhí)行handleNavigationBackRequest(返回原始頁(yè)面)拍嵌,settlementAccountList(跳轉(zhuǎn)到返款賬號(hào)列表頁(yè)面)
passProps遭赂,傳遞順序,狀態(tài)横辆,價(jià)格到償還頁(yè)面(此處這3個(gè)參數(shù)是從naive傳遞到index.ios.js撇他,index.ios.js再傳遞給Yet還款)
本地入口
let jsCodeLocation = URL(string: "http://localhost:8081/index.ios.bundle?platform=ios")let mockData:NSDictionary = ["orderid": self.orderId,"status" : self.orderDetailModel.status,"price"? : self.orderDetailModel.cost]let rootView = RCTRootView(bundleURL: jsCodeLocation,moduleName: "RNBackApply",initialProperties: mockData as [NSObject : AnyObject],launchOptions: nil)let vc = UIViewController()vc.view = rootViewself.navigationController?.isNavigationBarHidden = trueself.navigationController?.pushViewController(vc, animated: true)
jsCodeLocation RN執(zhí)行文件路徑,這里的路徑為開(kāi)發(fā)時(shí)使用狈蚤,發(fā)布時(shí)需要更換為main.jsbundle的路徑
mockData為從native傳遞到RN的數(shù)據(jù)
moduleName: "RNBackApply"與index.ios.js中registerComponent('RNBackApply', () => MECRM)對(duì)應(yīng)
3.構(gòu)建頁(yè)面
前面提到起始頁(yè)為Repayment困肩,那么Repayment是怎么實(shí)現(xiàn)如上圖的喃?以下為簡(jiǎn)要實(shí)現(xiàn)
'use strict';import React, { Component } from 'react';import {View,Text,StyleSheet,ScrollView,TouchableHighlight,//整塊區(qū)域有按壓效果AlertIOS,TouchableOpacity,//文字有按壓效果TextInput,Image,NativeModules,DeviceEventEmitter//通知} from 'react-native';import PayTypeChoice from './PayTypeChoice';//注意路徑是以當(dāng)前文件為準(zhǔn)export default class repayment extends Component {constructor(props) {super(props);var defaultMoney = (this.props["price"]*0.2<0.01?0.01:this.props["price"]);this.state = {events: {info: {id: '',orderId: this.props["orderid"].toString(),account: '',accountType: 1,accountName: '',bankName: '',branchName: '',money: defaultMoney.toString(),status: '',remark: '',failReason: '',}}};this._applySettlementRequest();this._accountInfoChoiced();}_accountInfoChoiced() {this.subscription = DeviceEventEmitter.addListener('accountInfoChoiced',(accountInfo) => {var newEvents = this.state.events;newEvents.info.account = accountInfo.account;newEvents.info.accountName = accountInfo.accountName;newEvents.info.accountType = accountInfo.accountType;newEvents.info.bankName = accountInfo.bankName;newEvents.info.branchName = accountInfo.branchName;this.setState({events: newEvents});})}_renderRow(title: string, subTitle: string, placeholder: string, onChangeText: Function, maxLength: int) {var status = this.props["status"];return ({title}{(status === 0 || status === 3)?:});}......_renderButton(onPress: Function) {var status = this.props["status"];var buttonString = '申請(qǐng)返款';switch (status) {case 0:var buttonString = '申請(qǐng)返款';break;case 1:var buttonString = '返款處理中';break;case 2:var buttonString = '已返款';break;case 3:var buttonString = '已拒絕脆侮,重新申請(qǐng)';break;case 4:var buttonString = '待審核';break;}var canPost = false;var orderInfo = this.state.events.info;if ((status === 0 || status === 3) && orderInfo.accountName.length > 0 && orderInfo.account.length > 0 && orderInfo.money.length > 0 ) {if (orderInfo.accountType === 2) {if (orderInfo.bankName.length > 0 && orderInfo.branchName.length > 0) {canPost = true;}} else {canPost = true;}}return ({canPost?{buttonString}:{buttonString}});}_onButtonPress() {var orderInfo = this.state.events.info;orderInfo.money = Number(orderInfo.money*100);if(isNaN(orderInfo.money)){AlertIOS.alert('請(qǐng)輸入正確的返款金額',)return;}var orderPrice = (this.props["price"]*100);if (orderInfo.money > orderPrice*0.8) {AlertIOS.alert('','當(dāng)前返款大于支付金額的80%锌畸,是否繼續(xù)?',[{text: '返回修改'},{text: '繼續(xù)發(fā)起', onPress: () => {var RNBridge = NativeModules.RNBridge;RNBridge.setSettlement(orderInfo,(error, events) => {if (error) {// console.error(error);} else {this._handleNavigationBackRequest();}})}}])return;}var RNBridge = NativeModules.RNBridge;RNBridge.setSettlement(orderInfo,(error, events) => {if (error) {// console.error(error);} else {this._handleNavigationBackRequest();}})};_applySettlementRequest() {var status = this.props["status"];// status參數(shù)說(shuō)明// 0? ? 未申請(qǐng)// 1? ? 返款中// 2? ? 返款成功// 3? ? 返款失敗if (status === 0) {return}var RNBridge = NativeModules.RNBridge;var orderid = this.props["orderid"].toString();RNBridge.applySettlement(orderid,(error, events) => {if (error) {console.error(error);} else {events.info.money = (events.info.money/100).toString();this.setState({events: events});}})}render() {var orderInfo = this.state.events.info;var status = this.props["status"];return ({this._renderPayTypeRow(() => {this.props.navigator.push({title: '返款方式',component: PayTypeChoice,barTintColor: '#7B9DFD',tintColor: 'white',passProps: {accountType: this.state.events.info.accountType,getPayType:(accountType)=>{var newEvents = this.state.events;newEvents.info.accountType = accountType;this.setState({events: newEvents});}}})})}{this._renderRow('姓名', orderInfo.accountName, '請(qǐng)輸入姓名', (accountName) => {var newEvents = this.state.events;newEvents.info.accountName = accountName;this.setState({events: newEvents});},10)}{(orderInfo.accountType === 2)?{this._renderRow('開(kāi)戶(hù)銀行', orderInfo.bankName, '請(qǐng)輸入開(kāi)戶(hù)銀行', (bankName) => {var newEvents = this.state.events;newEvents.info.bankName = bankName;this.setState({events: newEvents});})}{this._renderRow('開(kāi)戶(hù)支行', orderInfo.branchName, '請(qǐng)輸入開(kāi)戶(hù)支行', (branchName) => {var newEvents = this.state.events;newEvents.info.branchName = branchName;this.setState({events: newEvents});})}:null}......{this._renderButton(() => {this._onButtonPress();})});}}const styles = StyleSheet.create({......});
constructor 初始化數(shù)據(jù)靖避,這里的數(shù)據(jù)結(jié)構(gòu)和網(wǎng)絡(luò)請(qǐng)求結(jié)果保持一致蹋绽。
renderRow 函數(shù)以及被省略掉的其他renderXXXRow函數(shù)只是讓總的render函數(shù)沒(méi)那么臃腫,返回一些JSX片段筋蓖,在構(gòu)建界面中根據(jù)不同條件展示不同樣式是常見(jiàn)需求卸耘,但是JSX中不支持 if.else,只支持三目運(yùn)算符?:,在上面代碼中多次用到。
需求功能1:點(diǎn)擊返款方式粘咖,跳轉(zhuǎn)到返款方式選擇頁(yè)面蚣抗,然后把選擇的方式回傳。
這里頁(yè)面?zhèn)髦挡捎玫姆绞绞菍⑿薷姆悼罘绞胶蟮牟僮髯鳛橐粋€(gè)函數(shù)傳遞給下一個(gè)頁(yè)面瓮下,實(shí)現(xiàn)如下翰铡。
Repayment.js
{this._renderPayTypeRow(() => {this.props.navigator.push({title: '返款方式',component: PayTypeChoice,barTintColor: '#7B9DFD',tintColor: 'white',passProps: {accountType: this.state.events.info.accountType,getPayType:(accountType) => {var newEvents = this.state.events;newEvents.info.accountType = accountType;this.setState({events: newEvents});}}})})}
PayTypeChoice.js
render() {return ({this._renderRow('支付寶', this.state.alipay,() => {this.props.getPayType(1);this.props.navigator.popToTop()})}{this._renderRow('銀行卡', this.state.bankcard,() => {this.props.getPayType(2);this.props.navigator.popToTop()})});}
Repayment.js中的getPayType就是傳遞到下一個(gè)頁(yè)面,當(dāng)返款方式選擇后以執(zhí)行的函數(shù)讽坏。在PayTypeChoice.js中當(dāng)cell點(diǎn)擊的時(shí)候?qū)⒎悼罘绞阶鳛閰?shù)傳入锭魔,例如this.props.getPayType(1),就將返款方式設(shè)置為了支付寶路呜。
需求功能2:點(diǎn)擊右上角圖標(biāo)迷捧,跳轉(zhuǎn)到返款賬號(hào)列表頁(yè)织咧,然后把選擇的賬號(hào)信息帶回來(lái)填充頁(yè)面。
如之前所述漠秋,點(diǎn)擊圖標(biāo)跳轉(zhuǎn)的邏輯是寫(xiě)在index.ios.js文件中的
_settlementAccountList() {var status = this.props["status"];if (status === 0 || status === 3) {this.refs['nav'].push({title: '返款人信息表',component: SettlementAccountList,barTintColor: '#7B9DFD',tintColor: 'white',passProps: {}})}}
想通過(guò)剛才傳遞函數(shù)的方式達(dá)到頁(yè)面?zhèn)髦刁厦桑敲磇ndex.ios.js就要先獲取到Repayment用于回調(diào)的函數(shù),然后再傳遞給SettlementAccountList庆锦。很麻煩捅位,并且我嘗試了一下沒(méi)成功。這種時(shí)候搂抒,通知就顯得非常簡(jiǎn)單粗暴了艇搀,運(yùn)用React Native中的通知組件DeviceEventEmitter,頁(yè)面?zhèn)髦刀疾皇鞘聝骸?/p>
當(dāng)賬號(hào)信息被選擇時(shí)在SettlementAccountList中發(fā)送通知
_onPressCell(rowData: string) {this.props.navigator.popToTop()DeviceEventEmitter.emit('accountInfoChoiced', rowData);}
在Repayment中接收通知
_accountInfoChoiced() {this.subscription = DeviceEventEmitter.addListener('accountInfoChoiced',(accountInfo) => {var newEvents = this.state.events;newEvents.info.account = accountInfo.account;newEvents.info.accountName = accountInfo.accountName;newEvents.info.accountType = accountInfo.accountType;newEvents.info.bankName = accountInfo.bankName;newEvents.info.branchName = accountInfo.branchName;this.setState({events: newEvents});})}
需求功能3:在進(jìn)入頁(yè)面時(shí)拉取之前填寫(xiě)的返款信息求晶,點(diǎn)擊左上的返回按鈕回到Native頁(yè)面焰雕,以及返款賬號(hào)信息頁(yè)面拉取已有的信息。這3點(diǎn)都是調(diào)用的Native方法誉帅。雖然RN也有網(wǎng)絡(luò)請(qǐng)求方法,但是APP中的網(wǎng)絡(luò)請(qǐng)求會(huì)有公共參數(shù)右莱、公共的鑒權(quán)方法蚜锨、錯(cuò)誤處理等,所以網(wǎng)絡(luò)請(qǐng)求還是選擇走Native的好慢蜓。
創(chuàng)建待RN調(diào)用的Native方法的步驟亚再,在官方文檔中也講得很清楚,這里貼出我寫(xiě)的代碼片段(因?yàn)镺bjective-C寫(xiě)著更方便就沒(méi)用Swift晨抡,偷懶了一下)
RNBridge.m
#import "RNBridge.h"#import #import @implementation RNBridgeRCT_EXPORT_MODULE();RCT_EXPORT_METHOD(back){dispatch_async(dispatch_get_main_queue(), ^{UITabBarController *tabvc = (UITabBarController *)[self getCurrentVC];UINavigationController *navi = [tabvc selectedViewController];navi.navigationBarHidden = NO;[navi popViewControllerAnimated:YES];});}//獲取返款信息RCT_EXPORT_METHOD(applySettlement:(NSString *)orderID callback:(RCTResponseSenderBlock)callback){dispatch_async(dispatch_get_main_queue(), ^{UITabBarController *tabvc = (UITabBarController *)[self getCurrentVC];UINavigationController *navi = [tabvc selectedViewController];UIViewController * vc = navi.viewControllers.lastObject;[vc startAnimating];NSString *path = [NSString stringWithFormat:@"/order/%@/applySettlement",orderID];[NetworkTool GET:path parameters:nil successHandler:^(id _Nonnull result) {[vc stopAnimating];callback(@[[NSNull null], result]);} failureHandler:^(NSError * _Nullable error) {[vc stopAnimating];callback(@[error.localizedDescription, [NSNull null]]);}];});}//設(shè)置返款信息RCT_EXPORT_METHOD(setSettlement:(NSDictionary *)orderInfo callback:(RCTResponseSenderBlock)callback){dispatch_async(dispatch_get_main_queue(), ^{UITabBarController *tabvc = (UITabBarController *)[self getCurrentVC];UINavigationController *navi = [tabvc selectedViewController];UIViewController * vc = navi.viewControllers.lastObject;[vc startAnimating];NSString *orderID = orderInfo[@"orderId"];NSString *path = [NSString stringWithFormat:@"/order/%@/applySettlement",orderID];[NetworkTool POST:path parameters:orderInfo successHandler:^(id _Nonnull result) {[vc stopAnimating];callback(@[[NSNull null], result]);} failureHandler:^(NSError * _Nullable error) {[vc stopAnimating];callback(@[error.localizedDescription, [NSNull null]]);}];});}//返款人信息表RCT_EXPORT_METHOD(getSettlementAccount:(NSInteger)start callback:(RCTResponseSenderBlock)callback){dispatch_async(dispatch_get_main_queue(), ^{UITabBarController *tabvc = (UITabBarController *)[self getCurrentVC];UINavigationController *navi = [tabvc selectedViewController];UIViewController * vc = navi.viewControllers.lastObject;[vc startAnimating];NSString *path = [NSString stringWithFormat:@"/order/getSettlementAccount?start=%ld&limit=%d",(long)start,100];[NetworkTool GET:path parameters:nil successHandler:^(id _Nonnull result) {[vc stopAnimating];callback(@[[NSNull null], result]);} failureHandler:^(NSError * _Nullable error) {[vc stopAnimating];callback(@[error.localizedDescription, [NSNull null]]);}];});}
在RN中調(diào)用返回方法
_handleNavigationBackRequest() {var RNBridge = NativeModules.RNBridge;RNBridge.back();}
在RN中獲取已填寫(xiě)的返款信息
_applySettlementRequest() {var status = this.props["status"];// status參數(shù)說(shuō)明// 0? ? 未申請(qǐng)// 1? ? 返款中// 2? ? 返款成功// 3? ? 返款失敗if (status === 0) {return}var RNBridge = NativeModules.RNBridge;var orderid = this.props["orderid"].toString();RNBridge.applySettlement(orderid,(error, events) => {if (error) {console.error(error);} else {events.info.money = (events.info.money/100).toString();this.setState({events: events});}})}
4.調(diào)試
在模擬器中 command+D 調(diào)出RN的菜單,點(diǎn)擊Debug JS Remotely氛悬。
在需要調(diào)試的代碼前面加debugger,例如
_onButtonPress() {debuggervar orderInfo = this.state.events.info;orderInfo.money = Number(orderInfo.money*100);if(isNaN(orderInfo.money)){AlertIOS.alert('請(qǐng)輸入正確的返款金額',)return;}......};
簡(jiǎn)陋耘柱,夠用?(°?‵?′??)
5.上線以及熱更新
上線的時(shí)候需要將代碼中的jsCodeLocation修改一下
//let jsCodeLocation = URL(string: "http://localhost:8081/index.ios.bundle?platform=ios")let jsCodeLocation = Bundle.main.url(forResource: "main", withExtension: "jsbundle")
這個(gè)main.jsbundle是需要手動(dòng)生成的如捅,生成方法如下:
1.在React Native項(xiàng)目根目錄下運(yùn)行 npm start2.使用curl命令生成 main.jsbundlecurl http://localhost:8081/index.ios.bundle -o main.jsbundle
這樣進(jìn)入RN頁(yè)面的時(shí)候,頂上就不再有提示信息了调煎。如果提示找不到這個(gè)main.jsbundle文件镜遣,記得把main.jsbundle拖到iOS工程中引用一下。
打開(kāi)main.jsbundle文件士袄,你會(huì)發(fā)現(xiàn)里面包含了你所寫(xiě)的所有JS文件內(nèi)容悲关。所以其實(shí)你寫(xiě)的RN邏輯全在這里面。那么RN的熱更新就很好理解了娄柳,更新這個(gè)文件就好了寓辱。不管你自己實(shí)現(xiàn)還是選擇什么第三方熱更新方案,都是在各種花式更新這個(gè)main.jsbundle文件而已赤拒。
6.一些補(bǔ)充和問(wèn)題(碎碎念)
之前只講了推跳轉(zhuǎn)頁(yè)面秫筏,模態(tài)喃诱鞠?舉例一發(fā)
{alert("closed")}}>Hello World! {this.setModalVisible(!this.state.modalVisible)}}>Hide Modal {this.setModalVisible(true)}}>Show Modal
另外補(bǔ)充一個(gè)小問(wèn)題,如果npm start命令不好使的時(shí)候跳昼,嘗試一下react-native start
還有一個(gè)遺留問(wèn)題般甲,返回原始頁(yè)面的時(shí)候我是調(diào)用的本地方法返回的,難道RN自己不能返回嗎鹅颊,我其實(shí)是嘗試這樣的敷存,也覺(jué)得這很理所當(dāng)然。打印本地的navi.viewControllers堪伍,最后的的UIViewController就是RN頁(yè)面锚烦,NavigatorIOS的流行方法調(diào)用了竟然沒(méi)反應(yīng),難道是我姿勢(shì)不對(duì)帝雇?
(lldb) po navi.viewControllers<__NSArrayI 0x600000254160>(,,)
RN官方提供了NavigatorIOS和導(dǎo)航儀涮俄,使用方法大同小異,總感覺(jué)帶個(gè)iOS版更貼近原生尸闸。不過(guò)都說(shuō)導(dǎo)航更涼爽彻亲。