[React Native Android 安利系列] 建立簡單 RN 應用(以js角度來看RN)

歡迎你們收看react-native-android系列教程,跟着本系列教程學習,能夠熟練掌握react-native-android的開發,你值得擁有
https://segmentfault.com/blog...css

書接上回,咱們已經掌握瞭如何使用android studio與reactnative搭建一個react的基礎環境,並使用其成功的製做出了一個hello world,接下來,咱們要探索一下如何利用react-native製做出比HelloWorld複雜一點的界面(雖然是個界面都比helloWorld複雜),順便一塊兒審視一些ReactNativeAndroid工程的目錄結構。前端

1. 目錄結構

首先咱們來回顧一下,咱們的helloReact工程的目錄結構。java

打開CMD,或者終端,咱們能夠看到helloReact工程下,有三個目錄,和三個文件,如圖1.1所示node

圖1.1react

1.1 android目錄     這個就是我們的安卓工程了。裏面存放着生成的android應用代碼。
1.2 IOS目錄         這個是IOS開發的目錄,以後的react-native ios篇,咱們再詳細聊一下。
1.3 index.android.js   這個是安卓版本的js入口。
1.4 index.ios.js   這個是ios版本的js入口。
1.5 package.json   這個是本項目,這裏記載着項目的基本數據和依賴項。
1.6 node_modules   這個是項目依賴的npm庫的代碼。其中固然也包括ReactNative代碼的源碼,在以後的章節裏面,咱們將會一塊兒來讀一下ReactNative的源代碼。

2. 查看項目js

咱們詳細來看一下index.android.js,這裏用的是es6的語法,不過對於通常作過前端的人來講,是能夠看懂了,作java的應該也大體能看懂這裏寫的是什麼。android

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

class hellowReact extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.android.js
        </Text>
        <Text style={styles.instructions}>
          Shake or press menu button for dev menu
        </Text>
      </View>
    );  
  }
}
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('hellowReact', () => hellowReact);

位於上方的1~8行是對於react-native依賴的導入ios

接下來9~25行,定義了一個react的類,一個簡單的類,只須要擁有render方法便可渲染,在render方法中,咱們返回了須要渲染的組件的組合。git

請注意,在render中返回的並非字符串,而是JSX語法的組件組合。這些組件渲染至APP中。而且在JSX中,咱們直接輸出了變量{styles.xxx},在jsx中,咱們的js變量如需輸出,則須要放置在界符中{}es6

再次注意,在這裏,咱們使用js去調用了react-native提供的原生組件,就像網頁上的HTML標籤同樣,這更接近web編程。接下來,咱們還會分享更多組件的用法。github

27~44行,則大體向咱們展現了react-native的樣式寫法。以一種js的方式去定義樣式表,可是屬性和取值,使用的也的確很像咱們親切的css

最後將45~46行,將寫好的組建,註冊至react-native。

3. 動手改寫,寫一個自定義的屬性

接下來,咱們要自定義一個變量,變量裏面填充好數據,待點擊後,讓View發生變化。
首先咱們給hellowReact類,添加構造方法:

class hellowReact extends Component {
  constructor(props) {
    super(props);
    // 定義了初始的狀態
    this.state = {
        word: 'hello'
    };
  }

  render() {
    // 在JSX中,直接使用state中定義的word->this.state.word,並進行輸出
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
            {this.state.word}
        </Text>
      </View>
    );
  }
}

構造方法中,指定了helloReact的state屬性,其中有一個word屬性。在這裏,咱們也把render方法改變一下。直接將helloReact組建的state中的word屬性,渲染至界面上,搖一搖手中打開的helloReact的APP,點擊reloadjs,從新加載咱們更改過的js(結果如圖3.1所示)

232558_LoqS_1177792.png
圖3.1

此時,咱們看到界面上渲染了,咱們的word,"hello"。

接下來,咱們須要再次對咱們的APP進行一些改造

class hellowReact extends Component {
  constructor(props) {
    super(props);
    this.state = {
        word: 'hello'
    };
  }
  // 更改state中word的函數
  changeWord() {
    // 更改狀態,將word變量,更改成'world'
    this.setState({
      word: 'world'
    });
  }

  render() {
    // 點擊時觸發changeWord函數,更改狀態
    return (
      <View style={styles.container} onTouchEnd={this.changeWord.bind(this)}>
        <Text style={styles.welcome}>
            {this.state.word}
        </Text>
      </View>
    );
  }
}

咱們在View發生touchEnd的時候,調用自定義函數,changeWord。該方法將調用方法setState,將state中的word進行更改。

緊接着,咱們再次在APP上reloadjs。渲染的仍是以前的hello,咱們點擊界面,則界面渲染爲"world"(如圖3.2所示)

233405_ktgz_1177792.png
圖3.2

4. 回顧一下,咱們都幹了什麼

經過上述的實踐,咱們發現,其實react將咱們的界面組件,看作一個狀態機,在定義的render方法中,咱們將"組件"與"狀態"的糅雜--JSX,告知react,react在用戶觸發了狀態變化時,幫咱們從新進行了渲染。這個行爲,在組件中的體現,就是setState。因而咱們驚喜的發現,咱們只要更改狀態(setState)就行了。至於渲染,則不用操心,咱們調用了setState,界面自動就被從新渲染了。

而事件綁定,也像極了web編程中的DOM上綁定onclick事件的作法。在touchEnd的時候,會觸發咱們預先設定好的回掉函數。

5. 建立一個react-native-android的簡單列表

接下來,咱們要一塊兒作一個列表項。首先,咱們引入react-native提供的組建,ListView。

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ListView
} from 'react-native';

import的列表中,最後加入ListView。

而後,咱們在constructor裏面,加入一個狀態

constructor(props) {
    super(props);
    var list = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      list: list.cloneWithRows(['hello', 'react', 'this', 'is', 'my', 'listView'])
    };
  }

是一個符合ListView格式的數據源。接下來,咱們在render中渲染這個ListView

render() {
    return (
      <View style={styles.container}>
        <ListView
          dataSource={this.state.list}
          renderRow={this.oneRow}
        />
      </View>
    );
  }

其中,renderRow屬性,指定的是,渲染ListView中每一項的方法。咱們能夠直接寫個比較簡單的text組件。

oneRow(oneItem) {
    return <Text>{oneItem}</Text>;
  }

咱們看看總體的代碼

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ListView
} from 'react-native';

class hellowReact extends Component {
  constructor(props) {
    super(props);
    var list = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      list: list.cloneWithRows(['hello', 'react', 'this', 'is', 'my', 'listView'])
    };
  }
  oneRow(oneItem) {
    // 提供列表中,每個item的渲染方式
    return <Text>{oneItem}</Text>;
  }
  render() {
    // 渲染中使用了列表
    return (
      <View style={styles.container}>
        <ListView
          dataSource={this.state.list}
          renderRow={this.oneRow}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
});

AppRegistry.registerComponent('hellowReact', () => hellowReact);

保存後,咱們reload一下新改好的js。結果如圖5.1所示

000502_fHJK_1177792.png
圖5.1

這裏,咱們學會了,如何使用js去調用react-native提供的原生組件。原生組件有不少,基本能覆蓋咱們平常開發須要的基礎組件(如剛剛的ListView/View/Text等),可是還有不少咱們個性化的需求,沒法知足的時候,咱們又該怎麼辦呢?這一系列會詳細講解React中js調用原生代碼的方法。

上述講解,能夠在這裏找到相關例子:

https://github.com/houyu01/re...

下節更精彩,咱們未來一塊兒看看android原生的小知識,增強咱們開發react-native的底層瞭解。不要走開,請關注我.....

若是喜歡本文請點擊下方的推薦哦,你的推薦會變爲我繼續更文的動力。

相關文章
相關標籤/搜索