1. 程式人生 > >React-Native部分API學習

React-Native部分API學習

一、react-navigation

1、常見的導航分類

  • StackNavigator :類似於普通的Navigator,螢幕上方導航欄 
  • TabNavigator:obviously, 相當於iOS裡面的TabBarController,螢幕下方標籤欄 
  • DrawerNavigator:抽屜效果,左側滑出這種效果。

2、整合

 npm install react-navigation --save

3、初始化路由,createStackNavigator(老式寫法:StackNavigator

import { createStackNavigator } from 'react-navigation';
const AppNavigator = createStackNavigator(StackRouteConfigs, StackNavigatorConfigs);

4、StackNavigator+TabNavigator結合使用實現頁面跳轉以及傳參

問題:子頁面跳轉到詳情頁面時,this.props.navigation中報錯undefined

this.props.navigation.navigate('Detail')

解決:在配置子頁面時將當前的this.props傳遞過去

<Component {...this.props} />

5、隱藏頂部導航欄以及底部tabbar實現:

 static navigationOptions = {
    tabBarVisible: false, // 隱藏底部導航欄
    header:null,  //隱藏頂部導航欄
  };

6、屬性介紹

navigationOptions:配置StackNavigator的一些屬性。
    title:標題,如果設定了這個導航欄和標籤欄的title就會變成一樣的,不推薦使用
    header:可以設定一些導航的屬性,如果隱藏頂部導航欄只要將這個屬性設定為null
    headerTitle:設定導航欄標題,推薦
    headerBackTitle:設定跳轉頁面左側返回箭頭後面的文字,預設是上一個頁面的標題。可以自定義,也可以設定為null
    headerTruncatedBackTitle:設定當上個頁面標題不符合返回箭頭後的文字時,預設改成"返回"
    headerRight:設定導航條右側。可以是按鈕或者其他檢視控制元件
    headerLeft:設定導航條左側。可以是按鈕或者其他檢視控制元件
    headerStyle:設定導航條的樣式。背景色,寬高等
    headerTitleStyle:設定導航欄文字樣式
    headerBackTitleStyle:設定導航欄‘返回’文字樣式
    headerTintColor:設定導航欄顏色
    headerPressColorAndroid:安卓獨有的設定顏色紋理,需要安卓版本大於5.0
    gesturesEnabled:是否支援滑動返回手勢,iOS預設支援,安卓預設關閉
screen:對應介面名稱,需要填入import之後的頁面
mode:定義跳轉風格
   card:使用iOS和安卓預設的風格
   modal:iOS獨有的使螢幕從底部畫出。類似iOS的present效果
headerMode:返回上級頁面時動畫效果
   float:iOS預設的效果
   screen:滑動過程中,整個頁面都會返回
   none:無動畫
cardStyle:自定義設定跳轉效果
   transitionConfig: 自定義設定滑動返回的配置
   onTransitionStart:當轉換動畫即將開始時被呼叫的功能
   onTransitionEnd:當轉換動畫完成,將被呼叫的功能
path:路由中設定的路徑的覆蓋對映配置
initialRouteName:設定預設的頁面元件,必須是上面已註冊的頁面元件
initialRouteParams:初始路由引數
// 定義配置
let StackNavigatorConfig = {
  headerMode: 'float', // 返回上級頁面時動畫效果: float:iOS預設的效果/screen:滑動過程中,整個頁面都會返回/none:無動畫
  navigationOptions: {
    headerBackTitle: null, // 設定跳轉頁面左側返回箭頭後面的文字,預設是上一個頁面的標題。可以自定義,也可以設定為null
    headerStyle: { // 設定導航條的樣式。背景色,寬高等
      backgroundColor: '#fff',
    },
    headerTitleStyle: { // 設定導航欄文字樣式
      fontWeight: 'normal',
      fontSize: 17,
      color: '#333',
    },
  },
};

// 使用
const NavigatorHeaderComponent = createStackNavigator(routes, StackNavigatorConfig);

二、StackViewStyleInterpolator

react-navigation升級2.0後,更改頁面切換動畫API發生改變,原本是使用CardStackStyleInterpolator的,更改後為StackViewStyleInterpolator

// 原: 
import CardStackStyleInterpolator
from 'react-navigation/src/views/CardStack/CardStackStyleInterpolator';
// 新:
import StackViewStyleInterpolator
from "react-navigation/src/views/StackView/StackViewStyleInterpolator";

三、Dimensions、StatusBar

import {
    Dimensions, // 用來獲取螢幕的寬高
    StatusBar, // 設定導航欄的顏色
} from 'react-native';
// 獲取螢幕的寬高
const {
    width,
    height
} = Dimensions.get('window');
// 設定狀態列的顏色為白色
// barStyle  enum('default','light-content')  列舉型別,僅支援iOS裝置。進行設定狀態列文字的顏色
<StatusBar barStyle={'light-content'} /> 

四、TouchableOpacity

 本元件用於封裝檢視,使其可以正確響應觸控操作。當按下的時候,封裝的檢視的不透明度會降低

<TouchableOpacity onPress={this._onPress.bind(this)} activeOpacity={1}>
  {this._renderRowTag()}
</TouchableOpacity>

五、Button

 onPress方法是必須實現的,不實現會有警告

不能直接設定style,需要在外層放一個View來設定樣式

// 按鈕的樣式,可以設定背景顏色,圓角、等屬性
<View style={styles.buttonStyle}>
 <Button
   title='按鈕名稱'
   color='#68758e'
   onPress={() => console.log('點選了按鈕')}
 />
</View>

六、FlatList

除以下示例中註釋API:

  • renderItem:固定回撥的引數:item,index,separators
  • ListEmptyComponent:需要返回一個Component,資料為空的時候的元件
  • ListHeaderComponent: 需要返回一個Component,頭部元件,需要注意他不是重新整理的那個元件,只是一個不同於普通item的頭部元件
  • horizontal: 一個布林值,true是水平,false是垂直,預設false
  • numColumns:是一個number,表明該FlatList是幾列
  • ItemSeparatorComponent: 需要返回一個Component,作為item之間的分割線
<FlatList
  data={this.state.list} // 資料來源
  keyExtractor={(item) => item.id.toString()} // 返回一個獨立Item的唯一標識,需要返回一個index
  renderItem={this._renderItem} // 渲染每行
  ListFooterComponent={this._renderFooter} // footer元件,可以用來實現“上拉載入”
  onEndReachedThreshold={0.1} // 決定當距離內容最底部還有多遠時觸發onEndReached回撥
  onEndReached={this._onRefreshMore} // 當列表達到底部的回撥,用來實現“上拉載入”
  refreshing={this.state.refreshing} // “下拉重新整理需實現”,控制是否處於重新整理狀態
  onRefresh={this._onRefresh} // “下拉重新整理需實現”,觸發重新整理的回撥
  refreshControl={
    <RefreshControl
      refreshing={this.state.refreshing}
      onRefresh={this._onRefresh}
      title="載入中..."
 />
} // 下拉重新整理的控制元件返回,如果需要自定義的話,可實現
/>

另外提供的一些scroll方法,比如滾動到底部,滾動到具體item,滾動多少距離等

scrollToEnd //滾動到底部
scrollToIndex //滾動到第幾個item
scrollToItem //滾動到某個item 
scrollToOffset //滾動多少距離
recordInteraction //告訴列表滾動傳送了,會去呼叫viewability的計算。
flashScrollIndicators //隨時顯示滾動指示器

可以對列表的“下拉重新整理”和“上拉載入”進行封裝使用,以後另開帖子說明,參考的網站如下:

七、Text

ellipsizeMode 文字應該如何被截斷,需要注意的是,它必須和numberOfLines(文字顯示的行數)搭配使用,才會發揮作用。預設值為tail
  head:從文字的開頭進行截斷,並在文字的開頭新增省略號,例如:…xyz。
  middle :從文字的中間進行截斷,並在文字的中間新增省略號,例如:ab…yz。
  tail:從文字的末尾進行截斷,並在文字的末尾新增省略號,例如:abcd…。
  clip :文字的末尾顯示不下的內容會被截斷,並且不新增省略號,clip只適用於iOS平臺
numberOfLines 文字顯示的行數,預設可多行展示
selectable  預設值為false,為true時可以被選擇並複製到系統剪下板中
selectionColor 文字被選擇時的高亮顏色	Android系統生效
adjustsFontSizeToFit 預設值為false,為true時字型會自動縮小,以適應給定的樣式約束	iOS系統生效
minimumFontScale adjustsFontSizeToFit屬性為true時,設定字型的最小縮放比例,取值範圍為0.01~1.0	iOS系統生效
<Text style={styles.titleStyle}>我是標題</Text>
// 標題加粗
titleStyle: {
   marginLeft: 12, // 距離左邊邊距
   color: '#000000', // 文字顏色
   fontSize:16, // 文字大小
   fontWeight: "bold", // 加粗
   width: 100 // 文字寬度
}

八、FlexBox佈局在RN中的基本用法

九、實現懸浮按鈕

問題:React Native中position只有absolute和relative兩個值;並沒有fixed值

解決:將這個懸浮按鈕寫在ScrollView外部即可

return (
    <View>
        <ScrollView>
           <View>
               //內容滾動部分
           </View>             
        </ScrollView>
           <View>
               //懸浮按鈕的部分  
               <Button />
           </View>
    </View>
);

十、TextInput

問題:TextInput控制元件在未設定寬度時候會出現超出螢幕的情況,且直接設定控制的marginRight:12不生效,如下圖所示

解決:若要實現如下圖所示效果,且文字框距離右側有12px的寬度:

此處注意“justifyContent: 'space-between'”樣式的兩端對齊,相對於兩個元素的生效,將右側(inputText+12px的空白View)封裝成一個View

// render部分,自定義控制元件整體
<View style={styles.inputTextContainer}>
    <Text style={styles.inputTitleStyle}>{title}</Text>
    <View style={styles.inputRightStyle}>
        <TextInput
            style={styles.inputTextStyle}
            placeholder='請輸入'
            underlineColorAndroid="transparent"
        /> 
        <View style={styles.inputRightViewStyle} />
    </View>
</View>
// css樣式部分
const styles = StyleSheet.create({
    // 輸入框內容
    inputContainer: {
        marginTop: 10
    },
    // 一行的輸入框內容
    inputTextContainer: {
        flexDirection: 'row',
        height:58,
        backgroundColor: '#ffffff',
        alignItems: 'center',
        justifyContent: 'space-between'
    },
    // 文字框標題部分
    inputTitleStyle: {
        fontSize: 16,
        color: '#20304b',
        marginLeft: 12,
        width: '30%'
    },
    // 文字框右側部分
    inputRightStyle: {
        flexDirection: 'row',
        width: '70%'
    },
    // 文字框
    inputTextStyle: {
        fontSize: 16,
        marginLeft: 12,
        paddingLeft: 5,
        paddingRight: 5,
        textAlign: 'right',
        width: '88%'
    },
    // 文字框右側12px的寬度
    inputRightViewStyle: {
        width: 12,
    }
})

十一、StyleSheet

提供CSS樣式表,使程式碼佈局清晰

使用屬性hairlineWidth用來繪製線條

const styles = StyleSheet.create({
    // 分割線樣式
    separatorStyle: {
        backgroundColor: '#dfdfdf',
        height: StyleSheet.hairlineWidth, // 屬性hairlineWidth繪製線條,這一常量定義了當前平臺上的最細的寬度。可以用作邊框或是兩個元素間的分隔線
    },
})

持續更新