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

ShaXpr 9年前發布 | 10K 次閱讀 ReactNative 移動開發 React Native flexbox

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

  1. 函數綁定
  2. FlexBox 布局

一:函數綁定

首先來看一段代碼片段:

 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中的一段:

<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

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

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

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

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

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

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

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

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

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

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

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

 

來自: http://www.himigame.com/react-native/2222.html

 

 本文由用戶 ShaXpr 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!