【REACT NATIVE 系列教程之三】函數綁定與FLEXBOX是用好REACT的基礎

本站文章均爲 李華明Himi 原創,轉載務必在明顯處註明: 
轉載自【黑米GameDev街區】 原文鏈接: http://www.himigame.com/react-native/2222.html


Himi在寫React 時主要遇到兩個知識點覺得很有必要跟大家一起回顧下。

  1. 函數綁定

  2. FlexBox 佈局

   一:函數綁定

首先來看一段代碼片段:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

constructor(props) {

      super(props);

      this.state = {

         myName:'I am MyName!',

      };

  }

componentWillMount() {

    this.state.myName='cwm';

  }

  

  testFun1(){

    this.state.myName='tf1';

    Alert.alert('Himi', ' testFun1 ');

    

  }

  testFun2(){

    Alert.alert('Himi', ' testFun2 ');

  }

在state中聲明瞭myName

constructor: 組件的構造函數

componentWillMount : 組件預加載前調用的生命週期函數

testFun1、 testFun2 :是兩個自定義的函數。

 

繼續看render中的一段:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<TouchableHighlight

          underlayColor='#4169e1'

          onPress={this.testFun1}  

          >

            <Image

            source={require('./res/himi.png')}

            style={{width: 70, height: 70}}

            />

        </TouchableHighlight>

 

        <TouchableHighlight

          underlayColor='#4169e1'

          onPress={this.testFun2}  

          >

            <Image

            source={require('./res/himi.png')}

            style={{width: 70, height: 70}}

            />

        </TouchableHighlight>

這裏創建了兩個圖片組件且都添加了觸摸組件,分別綁定自定義的函數testFun1 與 testFun2

 

當我們點擊第一個圖片時會報錯,運行效果如下:(點擊查看動態圖)

user10    QQ20160512-0

錯誤是說this沒有undefined,原因是因爲當想在自定義的函數中使用this,那麼需要進行函數綁定。

函數綁定: 函數進行 bind(綁定) 可以確保在函數中的 this 作爲組件實例的引用,也就是說你想在自定義的函數中使用this,那麼請先進行將此函數bind(this)

那麼細心的童鞋會發現!爲什麼在 componentWillMount 函數中也使用了this卻通過了?因爲 componentWillMount 是組件的生命週期函數。

那麼常用的函數綁定方式有如下幾種:

1.  在生命週期函數中綁定,如下:

1

this.testFun1 = this.testFun1.bind(this)

 

2. 使用的地方直接綁定,如下:

1

onPress={this.testFun1.bind(this)}

 

3. 直接在使用的地方直接lambda,更方便  如下:

JavaScript

1

2

3

4

onPress={()=>{

     this.state.myName='tf1';

     Alert.alert('Himi', ' testFun1 ');

}}

 

   一:FlexBox 佈局

關於CSS 的FlexBox 本篇不重新贅述了,一來是因爲網上一搜一大把的教程,二來不一定有別人寫的仔細 – -… 。但是,Himi這裏推薦兩個鏈接,學習足以:

1. 詳細介紹與分析:  http://www.tuicool.com/articles/vQn6ZrU

2. 直觀的教程:http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html?utm_source=tuicool

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章