学习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.解决问题

相关文章
相关标签/搜索