學習ReactNative筆記

1.ES6語法

1.導出導入語法

可能報錯: Element type is invalidjavascript

ES5的導出導入語法:css

module.exports = Page2;
var NaviBar = require('./NaviBar');
複製代碼

ES6的導入導出語法:html

export  default class Page2 extends Component import NaviBar from './NaviBar';
複製代碼

Demo中使用了錯誤的導入方法java

import { AppRegistry } from 'react-native';
import { FirstView } from './Demo/ViewDemo.js';
複製代碼

正確的是node

import { AppRegistry } from 'react-native';
import FirstView from './Demo/ViewDemo.js'; 
複製代碼

導出帶有default,export default,引用時能夠不加大括號。導出沒有帶default,引用時要加大括號react

2.三點操做符

屬性前面的三個點(...props),是延展操做符。 在React中,延展操做符通常用於屬性的批量賦值。好比es6

var props = {};
props.foo = x;
props.bar = y;
var component = <Component {...props} />; 複製代碼

等同於chrome

var props = {};
props.foo = x;
props.bar = y;
var component = <Component foo={x} bar={y} />; 複製代碼

使用延展操做符的好處是,當你的屬性有所增長的時候,組件中的使用不須要去增長對應的屬性。npm

3.es5和es6更新狀態寫法對比

  • state
getInitialState(){
        return {
            currentPage: 0,
        }
},
複製代碼
constructor(props) {
        super(props);
        this.state = {
            selectedTab: tabBarItems[0].title,
        };
}
複製代碼
  • props
getDefaultProps(){
        return {
            duration: 3000,
        }
},
複製代碼
static defaultProps = {
    visible: false,
}
複製代碼

4.bind函數

5.模板字符串

6.ES6中箭頭函數加不加大括號的區別

  • 不加{},這時箭頭函數指向的就是這個函數的返回值
  • 種加{},要寫上返回值,加上return就跟不加大括號同樣

2.JS基礎知識

1.let和var

2.判斷數組中是否存在某個元素

3.遍歷對象的全部值

4.遍歷對象的全部屬性的key和value

5.javascript中let和var的區別

javascript中let和var的區別編程

6.點擊事件的兩種寫法

  • 箭頭函數
<TouchableOpacity
    //按下時透明度變化
    activeOpacity={0.5}
    onPress={() => this.activeEvent('點擊')}
>
    <Text style={{
        color: 'white',
        fontSize: 20,
    }}>登陸</Text>
</TouchableOpacity>

activeEvent(event) {
    Alert.alert(event)
}
複製代碼
  • bind綁定(推薦)
<View style={styles.contanier} >
        <Text onPress={this.timePlus.bind(this)}>點擊 </Text>
</View>
timePlus() {
    ......
}
複製代碼

7.數組的相關方法

arr = [2,4,5,7,8]

  • 遍歷
    • for循環
    • foreach循環,沒有返回值
    arr.forEach((item,index,array)=>{
    
        })
    複製代碼
    • map循環,map的回調函數中支持return返回值;return的是啥,至關於把數組中的這一項變爲啥(並不影響原來的數組,只是至關於把原數組克隆一份,把克隆的這一份的數組中的對應項改變了);
    var res = arr.map((item,index,arr )=>{ 
             return item*10; 
         }) 
         console.log(res);//-->[20, 40, 50, 70, 80]; 原數組拷貝了一份,並進行了修改
         console.log(arr);//-->[2, 4, 5, 7, 8]; 原數組並未發生變化
    複製代碼
  • 刪除
    • delete方法。delete刪除掉數組中的元素後,會把該下標出的值置爲undefined,數組的長度不會變
    delete arr[1]
        console.log(arr);//[2, undefined, 5, 7, 8]
    複製代碼
    • splice(index,len,[item]).該方法會改變原始數組。splice有3個參數,它也能夠用來替換/刪除/添加數組內某一個 index:數組開始下標 len: 替換/刪除的長度 item:替換的值,刪除操做的話 item爲空
    arr.splice(1,1)
        console.log(arr)//[2, 5, 7, 8]
    複製代碼
    arr.splice(1,2)
        console.log(arr)//[2, 7, 8]
    複製代碼

8.異步編程方法

1.使用回調函數

setTimeout(function() {
    console.log('Hello'); // 1秒後輸出"Hello"
    setTimeout(function() {
        console.log('Hi'); // 2秒後輸出"Hi"
    }, 1000);
}, 1000);
複製代碼

2.Promise對象

var waitSecond = new Promise(function(resolve, reject) {
    setTimeout(resolve, 1000);
});

waitSecond
    .then(function() {
        console.log("Hello"); // 1秒後輸出"Hello"
        return waitSecond;
    })
    .then(function() {
        console.log("Hi"); // 2秒後輸出"Hi"
    });
複製代碼

3.async/await

  • 申明耗時方法
waitSecond() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('sucess');
            }, 600);
        });
    }
複製代碼
  • 調用
async test() {
        const result = await this.waitSecond();
        console.warn(result);
    }
    this.test();
複製代碼

3.ReactNative知識

1.生命週期

不能在 shouldComponentUpdate方法中setState

新生命週期

  • 在構造方法裏setState({})
  • getDerivedStateFromProps是一個靜態函數,也就是這個函數不能經過this訪問到class的屬性,也並不推薦直接訪問屬性。而是應該經過參數提供的nextProps以及prevState來進行判斷,根據新傳入的props來映射到state。須要注意的是,若是props傳入的內容不須要影響到你的state,那麼就須要返回一個null,這個返回值是必須的,因此儘可能將其寫到函數的末尾。
static getDerivedStateFromProps(nextProps, prevState) {
    const {type} = nextProps;
    // 當傳入的type發生變化的時候,更新state
    if (type !== prevState.type) {
        return {
            type,
        };
    }
    // 不然,對於state不進行任何操做
    return null;
}
複製代碼

2.讓Text自適應,而且居中居中

parent: {
        backgroundColor:'blue',
        marginTop: 20,
        paddingTop: 50,
        paddingBottom: 50,
    },
    text: {
        fontSize: 20,
    }
複製代碼

父組件默認豎直顯示,此時Text組件默認橫向全屏

item: {
        backgroundColor:'blue',
        marginTop: 20,
        paddingTop: 50,
        paddingBottom: 50,
        justifyContent: 'center', 
        flexDirection: 'row'
    },
    text: {
        fontSize: 20,
        backgroundColor: 'red',
    }
複製代碼

添加屬性justifyContent: 'center', flexDirection: 'row',便可讓Text自適應大小,而且水平居中

3.RN中的this

React Native之this詳解

只要不在render函數的返回組件中使用this.props或者this.setState,那麼this就做用於當前操做對象
如何在render函數的return中使用this.props或者this.setState呢?

  • 在構造方法constrctor中綁定,綁定方式以下: this.函數名 = this.函數名.bind(this)
  • 在Render函數的組件中直接綁定,綁定方法以下: {this.函數名.bind(this)}
  • 使用箭頭函數,由於在ES6中,箭頭函數是本身的this值的,因此箭頭函數內的this值繼承自外圍做用域,所以,在箭頭函數中是能夠直接使用this的

4.React Native 全局變量Global

  • 建立全局變量文件
  • 導入
  • 直接使用

5.使用PropTypes類型檢查

由於在React 15.5.0 以後的版本中,將PropTypes從React庫中廢除掉了,所以在React 15.5.0 以後的版本,咱們就不要再已這種方式導出PropTypes了

import React, { Component, PropTypes} from 'react'
複製代碼

更換爲:

import { ViewPropTypes } from 'react-native'
import PropTypes from 'prop-types'
複製代碼

安裝prop-types庫

npm install prop-types --save
複製代碼

具體使用

import React, {Component} from 'react';
import {
    Text,
    View
} from 'react-native';
import PropTypes from 'prop-types'

export default class PropsTest extends Component{
    //設置默認屬性方法一
    static defaultProps={
        name:"小紅",
        age:20,
        sex:"男"
    }
    //類型檢測方法一
    /*static propTypes={ name:PropTypes.string, age:PropTypes.number, sex:PropTypes.string.isRequired, }*/
    render(){
        return (
            <View> <Text style={{fontSize:20,backgroundColor:'red'}}>你好: {this.props.name}</Text> <Text style={{fontSize:20,backgroundColor:'red'}}>年齡: {this.props.age}</Text> <Text style={{fontSize:20,backgroundColor:'red'}}>性別: {this.props.sex}</Text> </View>
        );
    }
}
//設置默認屬性方法二
/*PropsTest.defaultProps={ name:"小紅", age:20, sex:"男" }*/

//類型檢測方法二
PropsTest.propTypes={
    name:PropTypes.string,
    age:PropTypes.number,
    sex:PropTypes.string.isRequired,
}
複製代碼
# 數組類型
 PropTypes.array

 # 布爾類型
 PropTypes.bool

 # 函數類型
 PropTypes.func

 # 數值類型
 PropTypes.number

 # 對象類型
 PropTypes.object

 # 字符串類型
 PropTypes.string

 # 規定prop爲必傳字段
 PropTypes.func.isRequired

 # prop可爲任意類型, 任意不爲空對象
 PropTypes.any

#數組中元素的類型
PropTypes.any. arrayOf()

#React 元素
PropTypes.element

#類實例
PropTypes.instanceOf()

#每一個值的類型都是基本類型
PropTypes.node

#參數是數組, 指定傳的數據爲數組中的值,能夠當作枚舉類型使用
PropTypes.oneOf()

e.g-好比
color: PropTypes.oneOf(['red', 'blue', 'black'])

# 參數是數組, 指定傳的數據爲數組中的類型
 PropTypes.oneOfType()
 
 # 指定對象類型內部的結構定義
  PropTypes.shape()
  e.g-好比
  model:PropTypes.shape(
        {
          id: PropTypes.string,
          name: PropTypes.string 
        }
      )
複製代碼

5.默認Props

經過組件類的 defaultProps 屬性爲 props 設置默認值(static裏面的賦值操做會在app一運行 就會調用),實例以下:

export default class PropComponent extends Component {
    static defaultProps={
         name: '張三',
         sex:'man',
         tel:'13866666666'
        }
}
複製代碼

聲明defaultProps 屬性後,在遇到沒有被賦值的屬性時,就會讀取默認屬性值。

6.佈局詳細解析

佈局詳細解析

4.ReactNative三方庫

1.react-navigation2.0之前版本和3.0之後版本區別

2.0之前版本:
複製代碼
  • StackNavigator - 一次只渲染一個頁面,並提供頁面之間跳轉的方法。 當打開一個新的頁面時,它被放置在堆棧的頂部
  • TabNavigator - 渲染一個Tab選項卡,讓用戶能夠在幾個Tab頁面之間切換
  • DrawerNavigator - 提供一個從屏幕左側滑入的抽屜,相似bilibili和QQ的隱藏在左側的內容欄功能
新版本:
複製代碼
  • StackNavigator --> createStackNavigator

  • TabNavigator --> createBottomTabNavigator 也可使用

  • createStackNavigator 返回的結果須要再用createAppContainer包裹  const MainNavigator = createAppContainer(stackNavigator );\

3.x版本必須安裝react-native-gesture-handler

使用方法參考:https://reactnavigation.org/docs/en/3.x/getting-started.htmlhttps://zhuanlan.zhihu.com/p/67967551

注意: 多個navigation嵌套

假設第一個navigation配置了A和B,A裏面配置了第二個navigation,C和D。在C想要跳轉到A時,應該使用第一個navigation的navigate方法

5.工具使用

1.chrome調試自動打斷點的問題

在用chrome調試頁面時,一刷新頁面總會自動打斷點。全部的breakpoints都已經取消。把調試面板上的第5個按鈕從Deactivate breakpoints 改爲Activate breakpoints.解決問題

相關文章
相關標籤/搜索