React native development iOS

Source: Internet
Author: User

Reprinted from Kaich Blog (http://www.kaich.xyz) Contact react native

For technology, I prefer to chase new. Seeing the famous Facebook (open source model, releasing a lot of high-quality open-source frameworks) opened up a new framework for mobile cross-platform react native, so he couldn't wait to start touching it. The react native is designed so that the front-end development tasks can be developed on the mobile side (iOS programmers are much less than the web side), so there is this framework. For our iOS programmer there is no need to learn it, see it another feature: 跨平台 , but also a certain degree of understanding of web-side development, for a variety of purposes, learning react native why not!

I learned react Natvie experience

I've seen reports, thus touching react native, to write a small iOS app, which lasted just two weeks, basically can do the basic UI layout in everyday apps, requests (JSON and XML, the official only describes how JSON requests are requested), third-party package installation, use and modification. Whether it's iOS native development or the use of react native development, this can be achieved in a way that basically meets everyday needs. Here is an example code for react native:

var React = require (' react-native '); var {tabbarios, Navigatorios} = React;var App = React.createclass ({  render:func tion () {    return (      <TabBarIOS>        <tabbarios.item title= "React Native" selected={true}>          <navigatorios initialroute=/>        </TabBarIOS.Item>      </TabBarIOS>    );  });

From the above section of the code you can know about the knowledge needed to learn:

    • Basic CSS Knowledge (box model), you can refer to the CSS
    • CSS Flex Box Knowledge, you can refer to the layout of react-native
    • Javascrip Basics, refer to the basics of JavaScript, a bit deeper into the JavaScript,
    • NPM Package Manager
    • React JS, because react native is based on react JS, so we must first understand the react JS, that is, its specific principles, such as

      • React life cycle, functions called by each cycle, methods
      • React state machine, this is react's soul.
    • React native the use and properties of each component, debug, publish, this direct reference document is enough.

    • GitHub and other blogs to further enhance their capabilities

Write React Native Program

Work to good its line its prerequisite, react native official recommendation is atom, at the beginning of the period I want to use Vim to build react native programming environment, but too many functions do not prompt. For beginners or atom this with a hint of good, can increase our confidence.

Below I first share a small demo program: React-native-announce, can be used

git clone https://github.com/kaich/react-native-announce.git

To download it down. Compile and run to your emulator or device. You will find that it is an ugly list of interfaces. You can dynamically change the cell's height according to the content of the text after you click it. See the effect, now with Atom open Index.ios.js file, start the most critical content, slowly parse inside a few 100 lines of code.

"Use strict";

This first line of code means using the strict mode of JavaScript, which is the canonical pattern of syntax. There is no need to delve into this, you can also understand: JavaScript strict mode

var React = require (' react-native '); var {appregistry, StyleSheet, Text, View, ListView, touchablehighlight,} = React;

These two lines are the components that need to be imported, for example here we have imported: appregistry,stylesheet,text,view,listview,touchablehighlight these components.

var url = "Http://ios3.app.i4.cn/getNoticeList.xhtml?toolversion=520&model=iPhone7,1&pageno=1&idfa= 149dd67b-a5bb-4ee8-a83e-be91ebe7ece4&idfv=1c1d819e-5d0d-4059-83a5-ab1e6f9b7c2d&openudid= 667ee68f513ddd228edfc1c0eeab5f008dbb4733&osversion=8.1.3&udid= (NULL) &macaddress=020000000000& model=iphone7,1&certificateid=0&bundleid=0&isauth=1&isjail=0&authtime=1431077211& serialnumber=c39n9422g5qr&cid=200025&toolversion=520 "

This line declares the URL variable and is the interface address of the request. Next, because the data returned by the request is in the form of XML, but in react native does not provide the XML parsing library (possibly the XML form is obsolete), here we need to import the third-party XML parsing library, in this project I used the XMLDOM library. So how to import it? Here is the use of the above mentioned NPM package management. Go to the project root and run the command

NPM Install XMLDOM

After running successfully, you will see the Xmldom folder appears under the Node_modules folder. Here's how to import this library and use the

var domparser = require (' xmldom '). Domparser

After importing, you can use Domparser to parse the XML.

Next to the main part of the program, the following function of a function to see:

Getinitialstate:function () {   return {     datasource:new listview.datasource ({       rowhaschanged: (row1, row2) = > {Console.log ("Row1:" + row1.height + "Row 2:" + row2.height);  return true},     expanedcell:[],     data:[],   };},

Getinitialstate is called before the component is loaded, and is used to initialize the this.state, and the key to the entire program is to this.state the state machine, which, once changed, can trigger the corresponding logic of your interface update. Here are some of the following values:

    • Data sources for Datasource:listview
    • Expanedcell: Expanded cell array
    • Data: Store Request
componentDidMount: function(){   this.getAnnounces(); }

Componentdidmount UI component is called after loading, this.getannounces () custom method to send HTTP request request data

getannounces:function () {Console.log ("Start Request") Fetch (URL). t     Hen (response = Response.text ()). Then (ResponseText = = var results = new Array () var parser = new Domparser () var doc = parser.parsefromstring (responsetext, "Text/xml"). documentelement var ListNode = Doc.getelementsbytagname (" Noticelist ") [0] var list = listnode.getelementsbytagname (" notice ") for (Var i=0;i<list.length;i++) {var announce = new Object () var emelement = List.item (i) Announce.title = Emelement.getelementsbytagname ("title") [  0].firstchild.data announce.time = Emelement.getelementsbytagname ("Time") [0].firstchild.data Announce.detail =        Emelement.getelementsbytagname ("detail") [0].firstchild.data announce.height=0 Results[i]=announce}    This.state.data= results;       This.setstate ({datasource:this.state.datasource.cloneWithRows (results),})}); }

The Fetch method requests the data, parses it with XMLDOM after the request, and finally calls This.setstate to trigger the update of the list, showing what we requested. Next look at the body of the method render

  Render:function () {    return (     <listview Style={styles.container}        Datasource={this.state.datasource}        Renderrow={this.renderlistrow}      />    );  }

Defines a list whose data source is a This.state.datasource,cell rendering that calls This.renderlistrow. The data source request method has been done, then the cell rendering problem.

  Renderlistrow:function (announce) {    return (      <touchablehighlight onpress={() =>{this.rowclick ( Announce)}}>          <View>            <view  style={this.rowstyle (announce)} ref= ' Name ' >            <text style={styles.title}>{announce.title}</text>            <text style={styles.time}>{announce.time}</ text>            <text style={styles.detail}>{announce.detail}</text>          </View>          <view style={styles.seprator}/>       </View>        </TouchableHighlight>    );  },

Very simple structure, because need to be able to click on the cell, so the cell needs a clickable view of the most child view of the parent view, this is the three text of the child view, that is, iOS three Uilabel, respectively, is the title (name), Time, Detail (details), then a split-line seprator, inside the style is to control the layout of the inside style. The style has a change of height after the click and then control it.
Rowclick:function (announce) {   var selectedcells = This.state.expanedCell   if (announce.height==1)    {      Selectedcells.pop (announce)       announce.height =0;      This.setstate ({         datasource:this.state.datasource.cloneWithRows (this.state.data),  rowviewexpaned: Selectedcells,      });   }   else   {     Selectedcells.push (announce)      announce.height=1      this.setstate ({          datasource: This.state.datasource.cloneWithRows (This.state.data),  rowviewexpaned:selectedcells,      });   }   }

Click function if click Height is 0 then change the value to 1 and vice versa. Then it is called this.setstate trigger cell refresh, height, why did not see the height of the relevant content, is below.

  Rowstyle:function (announce) {    if (announce.height==1)       return styles.rowviewexpaned    else       Return Styles.rowview  },

If height is 1, returns the style of the extended cell, if height is 0 returns the normal cell style.

Because the whole stylesheet style is very simple, here is not said. See the code together with the document is easy to see, if you do not understand can leave a message, I will also put my understanding of CSS to add in, so that the novice can better understand, but also record my journey. This article is simple for beginners to read the features of each section, the most basic third-party use way. Next I will provide an entire project, rather than a simple page, to showcase the react native's strengths.

React native development iOS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.