React Native iOS零基礎(chǔ)自學(xué)常用API

1.AppRegistry

/*

? ? ? AppRegistry負(fù)責(zé)注冊(cè)運(yùn)行React Native應(yīng)用程序的入口袍暴。通過AppRegistry.registerComponent來注冊(cè),當(dāng)注冊(cè)完成后,

? ? ? Native系統(tǒng)(Objective-C)就會(huì)加載jsbundle文件并且觸發(fā)AppRegistry.runApplication運(yùn)行應(yīng)用。有以下方法:

? ? ? 1.registerConfig(config: Array):靜態(tài)方法削茁,注冊(cè)配置乳愉。

? ? ? 2.registerComponent(appKey: string, getComponentFunc: ComponentProvider):注冊(cè)入口組件柿祈。

? ? ? 3.registerRunnable(appKey: string, func: Function):注冊(cè)函數(shù)監(jiān)聽。

? ? ? 4.getAppKeys():獲取registerRunnable注冊(cè)的監(jiān)聽鍵暖眼。

? ? ? 5.runApplication(appKey: string, appParameters: any):運(yùn)行App惕耕。

*/

啟動(dòng)應(yīng)用時(shí),x-code日志輸出如下:2016-05-1913:48:28.777[info][tid:com.facebook.react.JavaScript] Running application"InformationServicesRN"withappParams: {"rootTag":1,"initialProps":{}}. __DEV__ ===true, development-level warning are ON, performance optimizations are OFF

其實(shí)诫肠,上面的日志是由runApplication打印出來的司澎,添加如下代碼:alert(AppRegistry.runApplication);AppRegistry.registerComponent('InformationServicesRN', () => app);

效果圖如下:

7074268D-FFDA-4E98-BCA8-29F8D11287EE.png

runApplication函數(shù)中的console.log()打印的正是我們啟動(dòng)時(shí)的日志欺缘。

也可以使用registerRunnable注冊(cè)一些AppKey:

AppRegistry.registerRunnable('vczero',function(){console.log('vczero'); }); AppRegistry.registerRunnable('react-native',function(){console.log('react-native'); }); alert(AppRegistry.getAppKeys());

效果如下:

83B2201B-825E-41A8-8C92-D3F915237659.png

2.AsyncStorage

/*

? ? AsyncStorage是一個(gè)簡(jiǎn)單的、具有異步特性的鍵值對(duì)的存儲(chǔ)系統(tǒng)挤安。相對(duì)整個(gè)App而言谚殊,它是全局的,應(yīng)該用于替代LocalStorage蛤铜。

? ? AsyncStorage提供了比較安全的方法供我們使用嫩絮。每個(gè)方法都有一個(gè)回調(diào)函數(shù),而回調(diào)函數(shù)的第一個(gè)參數(shù)都是錯(cuò)誤對(duì)象昂羡。如果發(fā)生錯(cuò)誤該對(duì)象就會(huì)展示錯(cuò)誤信息絮记,否則為null摔踱。所有的方法執(zhí)行后虐先,都會(huì)返回一個(gè)Promise對(duì)象。具體的方法如下所示:

? ? ? 1.static getItem(key: string, callback:(error, result)): 根據(jù)鍵來獲取值派敷,獲取的結(jié)果會(huì)在回調(diào)函數(shù)中蛹批。

? ? ? 2.static setItem(key: string, value: string, callback:(error)):設(shè)置鍵值對(duì)。

? ? ? 3.static removeItem(key: string, callback:(error)):根據(jù)鍵移除一項(xiàng)篮愉。

? ? ? 4.static mergeItem(key: string, value: string, callback:(error)):合并現(xiàn)有值和輸入值腐芍。

? ? ? 5.static clear(callback:(error)):清除所有的項(xiàng)目。

? ? ? 6.static getAllKeys(callback:(error)):獲取所有的鍵试躏。

? ? ? 7.static multiGet(keys, callback:(error, result)):獲取多項(xiàng)猪勇,其中keys是字符串?dāng)?shù)組。

? ? ? 8.static multiSet(keyValuePairs, callback:(error)):設(shè)置多項(xiàng)颠蕴,其中keyValuePairs是字符串的二維數(shù)組泣刹。

? ? ? 9.static multiRemove(keys, callback:(error)):刪除多項(xiàng),其中keys是字符串?dāng)?shù)組犀被。

? ? ? 10.static multiMerge(keyValuePairs, callback:(error)):多個(gè)鍵值對(duì)合并椅您,其中keyValuePairs是字符串的二維數(shù)組。

*/

以購物車為例寡键,來看看效果:

2.1 數(shù)據(jù)模型構(gòu)建

這里以購買水果為例定義一個(gè)靜態(tài)的商品數(shù)組掀泳。

varModel = [? {id:'1',title:'佳沛新西蘭進(jìn)口獼猴桃',desc:'12個(gè)裝',price:99,url:'http://vczero.github.io/ctrip/guo_1.jpg'},? {id:'2',title:'墨西哥進(jìn)口牛油果',desc:'6個(gè)裝',price:59,url:'http://vczero.github.io/ctrip/guo_2.jpg'},? {id:'3',title:'美國加州進(jìn)口車?yán)遄?,desc:'1000g',price:91.5,url:'http://vczero.github.io/ctrip/guo_3.jpg'},? {id:'4',title:'新疆特產(chǎn)西梅',desc:'1000g',price:69,url:'http://vczero.github.io/ctrip/guo_4.jpg'},? {id:'5',title:'陜西大荔冬棗',desc:'2000g',price:59.9,url:'http://vczero.github.io/ctrip/guo_5.jpg'},? {id:'6',title:'南非紅心西柚',desc:'2500g',price:29.9,url:'http://vczero.github.io/ctrip/guo_6.jpg'}];

2.2 列表項(xiàng)組件

用于渲染商品的圖片和名稱

//TouchableOpacity:透明觸摸。用戶點(diǎn)擊時(shí)西轩,點(diǎn)擊的組件會(huì)出現(xiàn)透明效果员舵。//resizeMode="contain" : 圖片縮放模型,"contain"自適應(yīng)所在容器模式//這里press點(diǎn)擊事件藕畔、url马僻、title都由父組件List傳遞過來varItem = React.createClass({render:function(){return({this.props.title});? }});

2.3 列表組件

varList = React.createClass({getInitialState:function(){return{count:0};? },//在組件第一次繪制之后,會(huì)調(diào)用 componentDidMount() 劫流,通知組件已經(jīng)加載完成巫玻。componentDidMount:function(){var_that =this;? ? AsyncStorage.getAllKeys(function(err, keys){if(err){//TODO:存儲(chǔ)取數(shù)據(jù)出錯(cuò)}//將存儲(chǔ)的商品條數(shù)反應(yīng)到按鈕上_that.setState({count: keys.length? ? ? });? ? });? },render:function(){varlist = [];for(variinModel){if(i %2===0){varrow = ();? ? ? ? list.push(row);//類似OC的數(shù)組addObject}? ? }varcount =this.state.count;varstr =null;if(count){? ? ? str ='丛忆,共'+ count +'件商品';? ? }return({list}去結(jié)算{str});? },goGouWu:function(){this.props.navigator.push({component: GouWu,title:'購物車'});? },press:function(data){varcount =this.state.count;? ? count ++;//改變數(shù)字狀態(tài)this.setState({count: count? ? });//AsyncStorage存儲(chǔ)AsyncStorage.setItem('SP-'+this.genId() +'-SP',JSON.stringify(data),function(err){if(err){//TODO:存儲(chǔ)出錯(cuò)}? ? });? },//生成隨機(jī)ID:GUIDgenId:function(){return'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c){varr =Math.random() *16|0,? ? ? ? ? v = c =='x'? r : (r &0x3|0x8);returnv.toString(16);? ? ? }).toUpperCase();? }});

2.4 購物車組件

購物車頁面

varGouWu = React.createClass({getInitialState:function(){return{data: [],price:0};? },render:function(){vardata =this.state.data;varprice =this.state.price;varlist = [];for(variindata){? ? ? price +=parseFloat(data[i].price);? ? ? list.push({data[i].title}? ? ? ? ? ? {data[i].desc}¥{data[i].price});? ? }varstr =null;if(price){? ? ? str =',共'+ price.toFixed(1) +'元';? ? }return({list}支付{str}清空購物車);? },componentDidMount:function(){var_that =this;? ? AsyncStorage.getAllKeys(function(err, keys){if(err){//TODO:存儲(chǔ)取數(shù)據(jù)出錯(cuò)//如果發(fā)生錯(cuò)誤仍秤,這里直接返回(return)防止進(jìn)入下面的邏輯}? ? ? AsyncStorage.multiGet(keys,function(errs, result){//TODO:錯(cuò)誤處理//得到的結(jié)果是二維數(shù)組//result[i][0]表示我們存儲(chǔ)的鍵熄诡,result[i][1]表示我們存儲(chǔ)的值vararr = [];for(variinresult){? ? ? ? ? arr.push(JSON.parse(result[i][1]));? ? ? ? }? ? ? ? _that.setState({data: arr? ? ? ? });? ? ? });? ? ? ? ? });? },clearStorage:function(){var_that =this;? ? AsyncStorage.clear(function(err){if(!err){? ? ? ? _that.setState({data:[],price:0});? ? ? ? alert('購物車已經(jīng)清空');? ? ? }//TODO:ERR});? }});

2.5 完整的功能

varReact =require('react-native');var{? AppRegistry,? StyleSheet,? Text,? View,? Image,? NavigatorIOS,? ScrollView,? AsyncStorage,? TouchableOpacity,} = React;varModel = [...];varItem = React.createClass({...});varList= React.createClass({...});varGouWu = React.createClass({...});varApp = React.createClass({? render:function(){return(? ? ? ? ? );? }});varstyles = StyleSheet.create({? container: {? ? flex:1,? },? row:{? ? flexDirection:'row',? ? marginBottom:10,? },? item:{? ? flex:1,? ? marginLeft:5,? ? borderWidth:1,? ? borderColor:'#ddd',? ? marginRight:5,? ? height:100,? },? img:{? ? flex:1,? ? backgroundColor:'transparent'},? item_text:{? ? backgroundColor:'#000',? ? opacity:0.7,? ? color:'#fff',? ? height:25,? ? lineHeight:18,? ? textAlign:'center',? ? marginTop:74},? btn:{? ? backgroundColor:'#FF7200',? ? height:33,? ? textAlign:'center',? ? color:'#fff',? ? marginLeft:10,? ? marginRight:10,? ? lineHeight:24,? ? marginTop:40,? ? fontSize:18,? },? list_item:{? ? marginLeft:5,? ? marginRight:5,? ? padding:5,? ? borderWidth:1,? ? height:30,? ? borderRadius:3,? ? borderColor:'#ddd'},? list_item_desc:{? ? flex:2,? ? fontSize:15},? list_item_price:{? ? flex:1,? ? textAlign:'right',? ? fontSize:15},? clear:{? ? marginTop:10,? ? backgroundColor:'#FFF',? ? color:'#000',? ? borderWidth:1,? ? borderColor:'#ddd',? ? marginLeft:10,? ? marginRight:10,? ? lineHeight:24,? ? height:33,? ? fontSize:18,? ? textAlign:'center',? }});AppRegistry.registerComponent('App', () => App);

效果如下:

40678F6D-64FD-4F56-B96A-F7827CB78053.png

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市诗力,隨后出現(xiàn)的幾起案子凰浮,更是在濱河造成了極大的恐慌,老刑警劉巖苇本,帶你破解...
    沈念sama閱讀 212,542評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件袜茧,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡瓣窄,警方通過查閱死者的電腦和手機(jī)笛厦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,596評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來俺夕,“玉大人裳凸,你說我怎么就攤上這事∪懊常” “怎么了姨谷?”我有些...
    開封第一講書人閱讀 158,021評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)映九。 經(jīng)常有香客問我梦湘,道長(zhǎng),這世上最難降的妖魔是什么件甥? 我笑而不...
    開封第一講書人閱讀 56,682評(píng)論 1 284
  • 正文 為了忘掉前任捌议,我火速辦了婚禮,結(jié)果婚禮上嚼蚀,老公的妹妹穿的比我還像新娘禁灼。我一直安慰自己,他們只是感情好轿曙,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,792評(píng)論 6 386
  • 文/花漫 我一把揭開白布弄捕。 她就那樣靜靜地躺著,像睡著了一般导帝。 火紅的嫁衣襯著肌膚如雪守谓。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,985評(píng)論 1 291
  • 那天您单,我揣著相機(jī)與錄音斋荞,去河邊找鬼。 笑死虐秦,一個(gè)胖子當(dāng)著我的面吹牛平酿,可吹牛的內(nèi)容都是我干的凤优。 我是一名探鬼主播,決...
    沈念sama閱讀 39,107評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼蜈彼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼筑辨!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起幸逆,我...
    開封第一講書人閱讀 37,845評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤棍辕,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后还绘,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體楚昭,經(jīng)...
    沈念sama閱讀 44,299評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,612評(píng)論 2 327
  • 正文 我和宋清朗相戀三年拍顷,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了抚太。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,747評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡菇怀,死狀恐怖凭舶,靈堂內(nèi)的尸體忽然破棺而出晌块,到底是詐尸還是另有隱情爱沟,我是刑警寧澤,帶...
    沈念sama閱讀 34,441評(píng)論 4 333
  • 正文 年R本政府宣布匆背,位于F島的核電站呼伸,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏钝尸。R本人自食惡果不足惜括享,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,072評(píng)論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望珍促。 院中可真熱鬧铃辖,春花似錦、人聲如沸猪叙。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,828評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽穴翩。三九已至犬第,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間芒帕,已是汗流浹背歉嗓。 一陣腳步聲響...
    開封第一講書人閱讀 32,069評(píng)論 1 267
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留背蟆,地道東北人鉴分。 一個(gè)月前我還...
    沈念sama閱讀 46,545評(píng)論 2 362
  • 正文 我出身青樓哮幢,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國和親志珍。 傳聞我的和親對(duì)象是個(gè)殘疾皇子家浇,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,658評(píng)論 2 350

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