React Native(iOS)新手小白零基礎(chǔ)自學(xué)(九)常用API及其實(shí)踐一

1.AppRegistry

/*
      AppRegistry負(fù)責(zé)注冊(cè)運(yùn)行React Native應(yīng)用程序的入口。通過(guò)AppRegistry.registerComponent來(lái)注冊(cè)宁昭,當(dāng)注冊(cè)完成后摧扇,
      Native系統(tǒng)(Objective-C)就會(huì)加載jsbundle文件并且觸發(fā)AppRegistry.runApplication運(yùn)行應(yīng)用局骤。有以下方法:
      1.registerConfig(config: Array<AppConfig>):靜態(tài)方法,注冊(cè)配置。
      2.registerComponent(appKey: string, getComponentFunc: ComponentProvider):注冊(cè)入口組件机久。
      3.registerRunnable(appKey: string, func: Function):注冊(cè)函數(shù)監(jiān)聽(tīng)。
      4.getAppKeys():獲取registerRunnable注冊(cè)的監(jiān)聽(tīng)鍵赔嚎。
      5.runApplication(appKey: string, appParameters: any):運(yùn)行App膘盖。
 */
啟動(dòng)應(yīng)用時(shí),x-code日志輸出如下:
2016-05-19 13:48:28.777 [info][tid:com.facebook.react.JavaScript] Running application 
"InformationServicesRN" with appParams: {"rootTag":1,"initialProps":{}}.
 __DEV__ === true, development-level warning are ON, 
performance optimizations are OFF
其實(shí)尤误,上面的日志是由runApplication打印出來(lái)的侠畔,添加如下代碼:
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ù)鍵來(lái)獲取值鹿蜀,獲取的結(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ù)組去件。
 */

以購(gòu)物車(chē)為例,來(lái)看看效果:

2.1 數(shù)據(jù)模型構(gòu)建
這里以購(gòu)買(mǎi)水果為例定義一個(gè)靜態(tài)的商品數(shù)組扰路。

var Model = [
  {
    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: '美國(guó)加州進(jìn)口車(chē)?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)組件
用于渲染商品的圖片和名稱(chēng)

//TouchableOpacity:透明觸摸尤溜。用戶點(diǎn)擊時(shí),點(diǎn)擊的組件會(huì)出現(xiàn)透明效果汗唱。
//resizeMode="contain" : 圖片縮放模型宫莱,"contain"自適應(yīng)所在容器模式
//這里press點(diǎn)擊事件、url哩罪、title都由父組件List傳遞過(guò)來(lái)

var Item = React.createClass({
  render: function(){
    return(
      <View style={styles.item}>
        <TouchableOpacity onPress={this.props.press}>
          <Image 
              resizeMode="contain" 
              style={styles.img}
              source={{uri:this.props.url}}>
            <Text numberOfLines={1} style={styles.item_text}>{this.props.title}</Text>
          </Image>
        </TouchableOpacity>
      </View>
    );
  }
});

2.3 列表組件

var List = 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() {
    var list = [];
    for(var i in Model){
      if(i % 2 === 0){
        var row = (
          <View style={styles.row}>
            <Item url={Model[i].url} 
              title={Model[i].title} 
              press={this.press.bind(this, Model[i])}></Item>
            <Item 
              url={Model[parseInt(i)+1].url} 
              title={Model[parseInt(i)+1].title} 
              press={this.press.bind(this, Model[parseInt(i)+1])}></Item>
          </View>);
        list.push(row); //類(lèi)似OC的數(shù)組addObject
      }
    }

    var count = this.state.count;
    var str = null;
    if(count){
      str = '绝葡,共'+ count + '件商品';
    }
    return (
      <ScrollView style={{marginTop:10}}>
        {list}
        <Text onPress={this.goGouWu} style={styles.btn}>去結(jié)算{str}</Text>
      </ScrollView>
    );
  },
  goGouWu: function(){
    this.props.navigator.push({
      component: GouWu,
      title:'購(gòu)物車(chē)'
    });
  },
  press:function(data){
    var count = 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:GUID
  genId:function(){
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0,
          v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      }).toUpperCase();
  }
});

2.4 購(gòu)物車(chē)組件
購(gòu)物車(chē)頁(yè)面

var GouWu = React.createClass({
  getInitialState: function(){
    return {
      data: [],
      price: 0
    };
  },
  render: function(){
    var data = this.state.data;
    var price = this.state.price;
    var list = [];
    for(var i in data){
      price += parseFloat(data[i].price);
      list.push(
        <View style={[styles.row, styles.list_item]}>
          <Text style={styles.list_item_desc}>
            {data[i].title}
            {data[i].desc}
          </Text>
          <Text style={styles.list_item_price}>¥{data[i].price}</Text>
        </View>
      );
    }
    var str = null;
    if(price){
      str = '深碱,共' + price.toFixed(1) + '元';
    }
    return(
      <ScrollView style={{marginTop:10}}>
        {list}
        <Text style={styles.btn}>支付{str}</Text>
        <Text style={styles.clear} onPress={this.clearStorage}>清空購(gòu)物車(chē)</Text>
      </ScrollView>
    );
  },
  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ǔ)的值
        var arr = [];
        for(var i in result){
          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('購(gòu)物車(chē)已經(jīng)清空');
      }
      //TODO:ERR
    });
  }
});

2.5 完整的功能

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  NavigatorIOS,
  ScrollView,
  AsyncStorage,
  TouchableOpacity,
} = React;

var Model = [...];
var Item = React.createClass({...});
var List = React.createClass({...});
var GouWu = React.createClass({...});

var App = React.createClass({
  render: function() {
    return (
      <NavigatorIOS
        style={styles.container}
        initialRoute={
          {
            component: List,
            title: '水果列表'
          }
        }/>
    );
  }
});

var styles = 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

89816ECE-0325-4976-94AD-41CBBC7E6878.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末敷硅,一起剝皮案震驚了整個(gè)濱河市功咒,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌绞蹦,老刑警劉巖力奋,帶你破解...
    沈念sama閱讀 211,290評(píng)論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異幽七,居然都是意外死亡景殷,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,107評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門(mén)澡屡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)猿挚,“玉大人,你說(shuō)我怎么就攤上這事驶鹉〖撸” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 156,872評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵室埋,是天一觀的道長(zhǎng)办绝。 經(jīng)常有香客問(wèn)我伊约,道長(zhǎng),這世上最難降的妖魔是什么孕蝉? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,415評(píng)論 1 283
  • 正文 為了忘掉前任屡律,我火速辦了婚禮,結(jié)果婚禮上昔驱,老公的妹妹穿的比我還像新娘疹尾。我一直安慰自己,他們只是感情好骤肛,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,453評(píng)論 6 385
  • 文/花漫 我一把揭開(kāi)白布纳本。 她就那樣靜靜地躺著,像睡著了一般腋颠。 火紅的嫁衣襯著肌膚如雪繁成。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 49,784評(píng)論 1 290
  • 那天淑玫,我揣著相機(jī)與錄音巾腕,去河邊找鬼。 笑死絮蒿,一個(gè)胖子當(dāng)著我的面吹牛尊搬,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播土涝,決...
    沈念sama閱讀 38,927評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼佛寿,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了但壮?” 一聲冷哼從身側(cè)響起冀泻,我...
    開(kāi)封第一講書(shū)人閱讀 37,691評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎蜡饵,沒(méi)想到半個(gè)月后弹渔,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,137評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡溯祸,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,472評(píng)論 2 326
  • 正文 我和宋清朗相戀三年肢专,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片焦辅。...
    茶點(diǎn)故事閱讀 38,622評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡博杖,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出氨鹏,到底是詐尸還是另有隱情欧募,我是刑警寧澤,帶...
    沈念sama閱讀 34,289評(píng)論 4 329
  • 正文 年R本政府宣布仆抵,位于F島的核電站跟继,受9級(jí)特大地震影響种冬,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜舔糖,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,887評(píng)論 3 312
  • 文/蒙蒙 一娱两、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧金吗,春花似錦十兢、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,741評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至卫袒,卻和暖如春宵呛,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背夕凝。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,977評(píng)論 1 265
  • 我被黑心中介騙來(lái)泰國(guó)打工宝穗, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人码秉。 一個(gè)月前我還...
    沈念sama閱讀 46,316評(píng)論 2 360
  • 正文 我出身青樓逮矛,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親转砖。 傳聞我的和親對(duì)象是個(gè)殘疾皇子须鼎,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,490評(píng)論 2 348

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