ReactNative学习笔记

文章目录


本套笔记参考这个视频教程做的,需要看视频的可以点链接去看

基础环境搭建

  • 安装nodejs

    – nodejs的版本应该>=12(推荐安装LTS版本)

    – npm config set registry https://registry.npm.taobao.org

    至于安卓环境大家自行百度(这里也需要用安卓环境,过于复杂就不多说了,需要使用一下Android Studio配一下安卓环境)

  • 安装Yarn

    npm install -g yarn
    
  • 安装reactNative脚手架

    npm install -g react-native-cli
    

创建项目

  • 初始化项目

    使用新命令,新版react-native所有原始的"react-native"命令前面都需要添加"npx"如下:

npx react-native init Demo

如果已经创建过其中一个版本的RN项目了,建议还是下载那个版本的(不用重复下载依赖,会先走缓存),重新下载新版本下载新版本的相关依赖,又会占用不少空间,运行命令如下

npx react-native init yx_rnDemo --version 0.70.6  // 指定版本号,一定要精确

如果碰到了以下情况

$ react-native init AwesomeProject
...
/usr/local/lib/node_modules/react-native-cli/index.js:302
  cli.init(root, projectName);
      ^
TypeError: cli.init is not a function
    at run (/usr/local/lib/node_modules/react-native-cli/index.js:302:7)
    at createProject (/usr/local/lib/node_modules/react-native-cli/index.js:249:3)
    at init (/usr/local/lib/node_modules/react-native-cli/index.js:200:5)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native-cli/index.js:153:7)
    at Module._compile (node:internal/modules/cjs/loader:1256:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Module._load (node:internal/modules/cjs/loader:960:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47

使用 npm -g list 查看已安装的 react-native 库

$ npm -g list
/usr/local/lib
├── 。。。
├── react-native-cli@2.0.1
├── 。。。

卸载 react-native -cli 库

npm uninstall -g react-native-cli
npm uninstall -g react-native  // 如果有,也一起卸载了

使用 npx react-native init 重新初始化项目

npx react-native init AwesomeProject

成功

  • 进入项目
cd 项目名
  • 运行项目
npm android
//本人电脑使用下面命令启动成功的
npm run android

如果运行项目以后碰到如下报错

Installing APK 'app-debug.apk' on 'BAH3-W59 - 10' for :app:debug
Installed on 1 device.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.5.1/userguide/command_line_interface.html#sec:command_line_warnings

说明Gradle版本不兼容,这里建议降低gradle的build版本,改为1.2.3

第二种方式升级你的React-Native至最新版本。(这种方式尝试过,没有测试出效果,依旧会提示)

打开 React Native 的项目, 修改Android/build.gradle 配置, 降低 gradle 的 build 为1.2.3版本.

buildscript {
   
   
    repositories {
   
   
        jcenter()
        mavenLocal()
    }
    dependencies {
   
   
        classpath 'com.android.tools.build:gradle:1.2.3' // 修改1.2.3
        classpath 'de.undercouch:gradle-download-task:2.0.0'


        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

这个时候还是会报错,需要重新设置 Gradle 的 Wrapper , 修改为2.2版本.
Gradle version 2.2 is required. Current version is 2.14.1
修改Gradle的Wrapper版本,需要修改android/griddle/wrapper/grade-wrapper.properties文件:
distributionUrl=https://services.gradle.org/distributions/gradle-2.2-all.zip

安装vscode插件

  • 插件名:

    ES7 React/Redux/GraphQL/React-Native snippets (with semi-colons)

    在这里插入图片描述

安装完输入rnc可以快速生成RN的类组件

安装完输入rnf可以快速生成RN的函数组件

在这里插入图片描述

调试工具

  • 模拟器调试

    – 模拟器都是安装到电脑上的,虚拟的手机界面

    – 模拟器一般随着Android Studio和Xcode一起安装

    – 启动应用,模拟器会随着一起启动

点击模拟器(使模拟器获取焦点)
快捷键ctrl+m
点选debug
自动跳转到浏览器上
  • 真机调试

    – 打开USB调试模式

    – 通过USB线将电脑和手机连起来

    – 启动应用,在手机上安装应用

  • 查看连接状态

adb devices

出现以下情况

C:\Users\22560>adb devices
List of devices attached
127.0.0.1:5555  offline
emulator-5554   device

可以发现我们想要连接的雷电模拟器的5555端口目前没有连接,只有emulator-5554被连接了,此时我们需要关闭这个连接,让5555端口连接上,可以继续往下操作

  • 执行端口号监控

    不用特意明白下面两行代码什么意思,只需要知道执行下面两行代码可以关闭5554端口,连接上5555端口就行了

    // adb -s 关闭的连接名 tcpip 指定连接的端口号
    adb -s emulator-5554 tcpip 5555
    // adb connect 连接的ip地址
    adb connect 127.0.0.1
    
  • 查看效果

C:\Users\22560>adb devices
List of devices attached
127.0.0.1:5555  device
emulator-5554   offline

如果使用的是模拟器调试的话,发现ctrl+m不能打开调试窗口的话,可以去下面的窗口打个d再返回模拟器就可以调出窗口了

在这里插入图片描述

基础语法

掌握React

  • JSX语法
  • 组件(分类,传参,属性,状态)
  • 生命周期
  • Hook API
  • Redux
  • 常用安装包

StyleSheet

StyleSheet是RN中声明样式的API

RN中的样式和CSS的不同

  • 没有继承性

    • RN中的继承只发生在Text组件上
  • 样式名采用小驼峰命名

    • fontSize VS font-size
  • 所有尺寸都是没有单位

    • width:200
  • 有些特殊样式名

    • marginHorizontal(水平外边距)
    • marginVertical(垂直外边距)

通过style属性直接声明

  • 属性值为对象:<组件 style={样式}/>
  • 属性值为数组:<组件 style={[{样式一},…,{样式N}]}/> 后面的样式会覆盖前面的

在style属性中调用StyleSheet声明的样式

  • 引入:import {StyleSheet , view} from ‘react-native’
  • 声明:const styles = StyleSheet.create({foo:{样式1},bar:{样式2}})
  • 使用:< View style={[styles.foo,styles.bar]}>内容</ View>

案例代码

import React, {
   
    Component } from 'react'
// 1.导入StyleSheet(安装完上面的插件后可以通过rncs快速创建)
import {
   
    Text, View, StyleSheet } from 'react-native'

export default class index extends Component {
   
   
  render () {
   
   
    return (
      <View>
        <Text style={
   
   {
   
    fontSize: 30 }}> textInComponent </Text>
        {
   
   /* 后面的样式会覆盖前面的 */}
        <Text style={
   
   [{
   
    color: 'red' }, {
   
    color: 'blue' }]}> textInComponent </Text>
        {
   
   /* 3.使用StyleSheet */}
        <Text style={
   
   [styles.h1]}>Hello RN</Text>
        <Text style={
   
   [styles.h2]}>Hello RN</Text>
      </View>
    )
  }
}

const styles = StyleSheet.create({
   
   
  // 2.声明StyleSheet的样式
  h1:{
   
   
    fontSize:40,
    fontWeight: 'bold'
  },
  h2:{
   
   
    fontSize:30,
    fontWeight: 'bold'
  }
})

Flexbox

术语

  • 容器(container)
    • 采用Flex布局的元素,称为Flex容器(flex container),简称’容器’
  • 项目(item)
    • 容器所有子元素,称为Flex项目(flex item) , 简称项目
  • 主轴(main axis)
  • 交叉轴(cross axis)

属性

  • flexDirection
    • 声明主轴方向: row(Web默认) | column (RN默认)

flexDirection属性使用的示例代码

import React, {
   
    Component } from 'react'
import {
   
    Text, StyleSheet, View,ScrollView } from 'react-native'

export default class index extends Component {
   
   
  render () {
   
   
    return (
      <View>
        <Text style={
   
   [styles.h2]}> 主轴方向 </Text>
        {
   
   /* View类似于div标签,只能显示固定区域内容,不可滚动,如果需要滚动需要引入scrollrow */}
        <ScrollView>
          <Text style={
   
   [styles.h3]}>flexDirection:'column'(默认)</Text>
          <View style={
   
   [styles.container]}>
            <Text style={
   
   [styles.itemBase]}>刘备</Text>
            <Text style={
   
   [styles.itemBase]}>关羽</Text>
            <Text style={
   
   [styles.itemBase]}>张飞</Text>
          </View>

          <Text style={
   
   [styles.h3]}>flexDirection:'column-reverse'</Text>
          <View style={
   
   [styles.container,styles.flexColumnReverse]}>
            <Text style={
   
   [styles.itemBase]}>刘备</Text>
            <Text style={
   
   [styles.itemBase]}>关羽</Text>
            <Text style={
   
   [styles.itemBase]}>张飞</Text>
          </View>

          <Text style={
   
   [styles.h3]}>flexDirection:'row'</Text>
          <View style={
   
   [styles.container,styles.flecRow]}>
            <Text style={
   
   [styles.itemBase]}>刘备</Text>
            <Text style={
   
   [styles.itemBase]}>关羽</Text>
            <Text style={
   
   [styles.itemBase]}>张飞</Text>
          </View>

          <Text style={
   
   [styles.h3]}>flexDirection:'row-reverse'</Text>
          <View style={
   
   [styles.container,styles.flexRowReverse]}>
            <Text style={
   
   [styles.itemBase]}>刘备</Text>
            <Text style={
   
   [styles.itemBase]}>关羽</Text>
            <Text style={
   
   [styles.itemBase]}>张飞</Text>
          </View>
        </ScrollView>
      </View>
    )
  }
}

const styles = StyleSheet.create({
   
   
  container: {
   
   
    height: 150,
    margin: 10,
    borderWidth: 1,
    borderColor: '#ddd'
  },
  h2: {
   
   
    fontSize: 30,
    marginHorizontal: 10
  },
  h3: {
   
   
    fontSize: 24,
    marginHorizontal: 10
  },
  itemBase: {
   
   
    height: 30,
    borderWidth: 1,
    borderColor: 'red',
    backgroundColor: '#dff',
    padding: 2,
    textAlign: 'center'
  },
  flexColumn:{
   
   
    flexDirection: 'column',
  },
  flexColumnReverse:{
   
   
    flexDirection: 'column-reverse',
  },
  flecRow:{
   
   
    flexDirection: 'row',
  },
  flexRowReverse:{
   
   
    flexDirection: 'row-reverse',
  }
})
  • justifyContent
    • 声明项目在主轴上的对齐方式
  • alignItems
    • 声明项目在交叉轴的对齐方式
  • flex
    • 声明项目在主轴上的尺寸比例

响应式布局

两种方式:

  • flexbox
  • Dimensions
    • import {Dimensions} from ‘react-native’
    • const windowWidth = Dimensions.get(‘window’).width
    • const windowHeight = Dimensions.get(‘window’).height

响应式布局案例代码

import React, {
   
    Component } from 'react'
// 引入DimenSions
import {
   
    Text, StyleSheet, View, Dimensions } from 'react-native'

// 响应式获取手机宽高
export default class index extends Component {
   
   
  render () {
   
   
    return (
      <View style={
   
   [styles.container]}>
        <View style={
   
   [styles.itemBase]}>
          <Text style={
   
   [styles.h3]}> 扫一扫 </Text>
        </View>
        <View style={
   
   [styles.itemBase]}>
          <Text style={
   
   [styles.h3]}> 付款码 </Text>
        </View>
        <View style={
   
   [styles.itemBase]}>
          <Text style={
   
   [styles.h3]}> 卡包 </Text>
        </View>
        <View style={
   
   [styles.itemBase]}>
          <Text style={
   
   [styles.h3]}> 出行 </Text>
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
   
   
  container: {
   
   
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  itemBase:{
   
   
    justifyContent:'center',
    alignItems: 'center',
    backgroundColor:'#00b38a',
    width:Dimensions.get('window').width/3,  //获取屏幕总宽度,除以4就是每个宽度
    height:Dimensions.get('window').height/7,
    borderWidth:1,
    borderColor:'yellow',
    // fontSize:30 //在RN没有样式继承,这个属性不会给子元素text标签,因此不会生效,只能重新给text标签加样式
  },
  h3:{
   
   
    fontSize:30
  }
})

组件和API

简介

  • RN中的核心组件,是对原生组件的封装

    • 原生组件:Androd或者ios内的组件
    • 核心组件:RN中最常用的,来在react-native的组件

    RN组件

    作用 RN组件 安卓视图 ios视图 HTML标签
    展示区块 View ViewGroup UIView div
    展示图片 Image ImageView UIImageView img
    展示文本 Text TextView UITextView p

核心组件

  • 基础组件
  • 交互组件
  • 列表视图
  • ios独有组件
  • Android独有组件
  • 其他
最常用的一些核心组件
import {
   
   
    View,  // 视图组件
    Text,  // 文本组件
    Alert, //警告框组件
    Button, //按钮组件
    Switch, //开关组件
    ActivityIndicator, //加载指示器组件
    TextInput, //输入框组件
    Touchable, //触碰组件(共三个)
    ScrollView, //滚动视图组件
    SectionList, //分组列表组件
    FlatList, //高效性能列表组件
    Animated, //动画组件
    StatusBar, //状态栏组件
    Image, //图片组件
    TouchableOpacity,
    Dimensions,
    StyleSheet,
    ImageBackground
} from 'react-native'
各核心组件的演示代码
Alert和Button(弹出框和按钮组件)
import React, {
   
    Component } from 'react'
import {
   
   
  View,  // 视图组件
  Text,  // 文本组件
  Alert, //警告框组件
  Button, //按钮组件
  StyleSheet,
} from 'react-native'

export default class alert01 extends Component {
   
   
  // 定义方法(这个方法里面定义两个按钮,分别为确认或者取消)
  createTwoButton = () => {
   
   
    Alert.alert(
      '警告标题',
      '警告内容',
      [
        {
   
   
          text: '取消',
          onPress: () => {
   
   
            console.log('点击了取消按钮')
          },
          style: 'cancel'
        },
        {
   
   
          text: '确认',
          onPress: () => {
   
   
            console.log('点击了确认按钮')
          },
          style: 'default'
        }
      ]
    )
  }

  // 定义三个按钮
  createTwoButtonAlert = () => {
   
   
    Alert.alert(
      '更新提升',
      '发现新版本,是否现在更新',
      [
        {
   
   
          text: '稍后再试',
          onPress: () => {
   
   
            console.log('稍后提醒我')
          },
          style: 'destructive'  //style有的手机能看到样式,有的看不到,这个可以省略
        },
        {
   
   
          text: '取消',
          onPress: () => {
   
   
            console.log('点击了取消按钮')
          },
          style: 'cancel'
        },
        {
   
   
          text: '确认',
          onPress: () => {
   
   
            console.log('点击了确认按钮')
          },
          style: 'default'
        }
      ]
    )
  }
  render () {
   
   
    return (
      <View style={
   
   [styles.container]}>
        {
   
   /* 按钮的title属性为展示的内容,onPress为点击事件,color为按钮背景色 */}
        <Button title='alart'
          onPress={
   
   () => {
   
   
            alert("我是一个按钮")
          }} />

        {
   
   /* 使用alert组件 */}
        <Button title='Alert.alert' onPress={
   
   () => {
   
   
          Alert.alert("我是按钮2")
        }}
          color={
   
   'red'}
        >
        </Button>

        <Button title='带确认和取消的按钮' onPress={
   
   
          this.createTwoButton
        }
          color={
   
   'blue'}
        >
        </Button>

        <Button title='带三个按钮的' onPress={
   
   
          this.createTwoButtonAlert
        }
          color={
   
   'tomato'}
        >
        </Button>
      </View>
    )
  }
}

const styles = StyleSheet.create({
   
   
  container: {
   
   
    flex: 1,
    justifyContent: 'space-around',
    alignItems: 'center'
  }
})
Switch和StatusBar(开关和状态栏组件)
import React, {
   
    Component } from 'react'
import {
   
    Text, StyleSheet, View, Switch, StatusBar } from 'react-native'

export default class SwitchAndStatusBar extends Component {
   
   
  // 定义一个函数,点击开关按钮控制状态条显隐
  constructor() {
   
   
    super()
    this.state = {
   
   
      hideStatusBar: false
    }
  }
  // 通过改变这个状态触发开关的功能和状态栏显隐
  toggleStatusBar = () => {
   
   
    this.setState({
   
   
      hideStatusBar: !this.state.hideStatusBar
    })
  }
  render () {
   
   
    return (
      <View style={
   
   [styles.container]}>
        {
   
   /*StatusBar: 状态条:hidden:控制状态条显隐,backgroundColor状态栏背景色(仅在安卓应用下有效),barStyle有三个值(代表状态栏图标的样式) */}
        <StatusBar
          hidden={
   
   this.state.hideStatusBar}
          backgroundColor={
   
   'red'}
          barStyle={
   
   'dark-content'}
        ></StatusBar>

        {
   
   /* Switch:开关按钮,trackColor定义开关状态颜色,thumbColor定义小圆点颜色,value按钮状态值(默认按钮不可用,只有定义了状态通过切换状态才可以) */}
        <Switch
          trackColor={
   
   {
   
   
            false: 'red',
            true: 'green',
          }}
          thumbColor={
   
   'blue'}
          value={
   
   this.state.hideStatusBar}
          onValueChange={
   
   
            this.toggleStatusBar
          }
        ><
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萧寂173

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值