React Native v0.55 学习笔记1

本文是React Native v0.55的学习笔记,涵盖了Hello World、Props、State、Style、宽高和基本布局FlexBox等内容。介绍了RN如何基于React的思想结合原生平台组件进行开发,讲解了组件、Props和State的概念,以及如何使用FlexBox进行灵活布局。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

React Native v0.55 学习笔记1

学习内容来自官网文档0.55版本

RN 是基于 React 的思想,相比于 web 的一些组件,RN 使用的是基于原生( android、ios )的组件。所以想用 RN 开发应用的话,就需要了解一些 React 方面的概念。例如 JSX,component,state 和 props。

Hello World

  1. RN 使用的是 JavaScript ,支持 ES6 的语法,官方文档中的示例大量使用了 ES6 的新特性。
  2. 在 UI 方面则是主要使用 JSX ——一种可以在 XML 标签中包裹 js 语句的语法。RN 内置很多标签,也支持自定义标签。
  3. Component 一个完整的应用必然是由许多个 component 组成的。一个 component 可以非常的简单,唯一需要做的事情就是实现 render函数,这个函数用来返回 JSX 用以渲染 UI.

Props

大多数的 component 都会通过不同的参数来实现自定义的不同功能,这些参数就被称为 props

  1. 例如 RN 中的 Image标签,其中 source这个属性就是用来控制图片源的。
import React, { Component } from 'react';
import { AppRegistry, Image } from 'react-native';

export default class Bananas extends Component {
  render() {
    let pic = {
      uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'
    };
    return (
      <Image source={pic} style={{width: 193, height: 110}}/>
    );
  }
}

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => Bananas);
  1. JSX 语法中,标签内部,使用一对花括号{}内容可以是 js 的表达式。
  2. 使用 this.props在自定义的componentrender方法中可以获取外部传入的参数,见下面的代码块。
  3. 下面的例子中,使用到了自定义component,在 JSX 中像内置的标签一样使用。
  4. View是一个非常常用容器标签,也是最基本的 UI 控件之一,支持flexbox布局、style、触摸事件处理以及无障碍功能处理。
import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native';

class Greeting extends Component {
  render() {
    return (
      <Text>Hello {this.props.name}!</Text>
    );
  }
}

export default class LotsOfGreetings extends Component {
  render() {
    return (
      <View style={{alignItems: 'center'}}>
        <Greeting name='Rexxar' />
        <Greeting name='Jaina' />
        <Greeting name='Valeera' />
      </View>
    );
  }
}

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => LotsOfGreetings);

State

propsstate是控制component的两种数据类型。前者由父类或者外部传入,在整个控件的生命周期中是固定不变的;后者则是用于一些有变化的数据

  1. 通常来说,在constructor方法中初始化state
  2. 通常来说,使用this.setState()方法来改变state的值。
import React,{Component} from 'react';
import {Text,Image,View} from 'react-native';

class Greeting extends Component{
  constructor(props){
    super(props);
    this.state = {isShowingText:true};
    setInterval(()=>{
      this.setState(previousState=>{
        return { isShowingText: !previousState.isShowingText };
      })
    },1000);
  }
  render() {
    let disPlay = this.state.isShowingText ? this.props.name : ' ';
      return (
          <Text style={{color:'#045d51'}}>{disPlay}</Text>
      );
  }
}

export default class HelloWorldApp extends Component{

  render(){
    return(
        <View style={{alignItems:'center'}}>
          <Greeting name='liu'/>
          <Greeting name='liulin'/>
          <Greeting name='liuru'/>
        </View>
    );
  }
}
  1. 实际使用中,很少有直接使用定时器来改变state的状态,而是跟踪数据流的变动。可以使用像Redux类似的状态容器来控制数据流,上面的例子中,可以使用Redux来改变state而不是直接调用setState方法。
  2. setState方法被调用时,标签所在的component会被重新渲染。这块的工作机制和React.js是一致的(暂时还没有去了解)。

Style

  1. 在 RN 中,使用 JS 的方式来定义组件的样式。所有的核心组件都支持名为style的属性,样式的属性名和属性值基本与 web 下 css 一致,只不过命名方式变成了驼峰式。
  2. style的属性可以是一个简单的 JS 对象,可以传入一个对象数组,对象数组中的对象如果有属性重复,以最后一个同名属性为准,这样也是实现了样式的继承
  3. 建议使用StyleSheet.create({})的方式来构建复用性比较高的样式对象。
export default class HelloWorldApp extends Component{
  render(){
    return(
        <View style={{alignItems:'center'}}>
          <Text style={styles.red}>just Red</Text>
          <Text style={styles.bigBlue}>just blue</Text>
          <Text style={[styles.bigBlue,styles.red]}>bigBlue,then red</Text>
          <Text style={[styles.red,styles.bigBlue]}>red,then bigBlue</Text>
        </View>
    );
  }
}
const styles = StyleSheet.create({
     bigBlue:{
       color:'blue', fontWeight:'bold', fontSize:30
     },
    red:{
     color:'red'
    }
});

宽高

  1. heightwidth分别表示控件的高度和宽度,需要注意到的是,宽度和高度的单位是与设备实际像素宽高无关的逻辑像素点(感觉类似 Android 中的 dp 和 sp 的感觉,具体的换算还需要研究)。
  2. 直接设置宽高的值,会使得控件在不同尺寸的屏幕上展示相同的大小。
<View>
        <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
        <View style={{width: 100, height: 100, backgroundColor: 'skyblue'}} />
        <View style={{width: 150, height: 150, backgroundColor: 'steelblue'}} />
      </View>
  1. 除了指定具体数值的方式外,宽高还可以弹性指定,利用flex这个属性,这个属性的属性值为数字,表示在允许的范围内,按照flex的值的比例动态设置宽高,类比于 Android 中LinearLayoutlayout_weight属性。但是需要注意的是,子控件使用flex属性且生效的前提是,父控件的宽高不为0,否则是不可见的
<View style={{flex:1}}>
          <View style={{flex:1,backgroundColor:'powderblue'}}/>
          <View style={{flex:2,backgroundColor:'skyblue'}}/>
          <View style={{flex:3,backgroundColor:'steelblue'}}/>
        </View>

基本布局 FlexBox

使用FlexBox进行布局,使用flexbox的策略可以指定一个容器内部子控件的布局方式,有三种基本的布局样式,flexDirectionalignItemsjustifyContent

  1. Flex Direction
    componentstyle属性中添加flexDirection属性是确定子控件布局的坐标轴主轴是哪个。可选属性值有四个,rowrow-reversecolumn(默认选项)和column-reverse

如何理解坐标轴主轴
row代表的是x轴,即子控件在x轴方向上按照布局顺序从左到右顺序布局,x轴的方向是左右方向,所以展示效果上来看,就是水平布局(horizontal)
column代表的是y轴,即子控件在y轴方向上按照布局顺序从上到下顺序布局,y轴的方向是上下方向,所以展示效果是纵向布局(vertical)

enter image description here

<View>
            <View style={{height:200,flexDirection:'row'}}>
                <View style={{flex:1,backgroundColor:'powderblue'}}/>
                <View style={{flex:2,backgroundColor:'skyblue'}}/>
                <View style={{flex:3,backgroundColor:'steelblue'}}/>
            </View>
            <View style={{height:200,flexDirection:'column'}}>
                <View style={{flex:3,backgroundColor:'powderblue'}}/>
                <View style={{flex:2,backgroundColor:'skyblue'}}/>
                <View style={{flex:1,backgroundColor:'steelblue'}}/>
            </View>
        </View>

row-reversecolumn-reverse则是颠倒了主轴方向,这个方向指的是布局绘制方向,以row举例默认状态下是从左侧开始,从左到右顺序绘制,加上-reverse后,变成了从右侧开始,从右到左顺序绘制,并且justifyContent的属性值的含义也随着坐标轴方向的变化而取反了。
enter image description here

<View style={{
                height:100,
                flexDirection:'row',
                justifyContent:'flex-start',
                alignItems:'center',
                backgroundColor:'#878787'
            }}>
                <View style={[styles.hw50,{backgroundColor:'#0bffd3'}]}/>
                <View style={[styles.hw50,{backgroundColor:'powderblue'}]}/>
                <View style={[styles.hw50,{backgroundColor:'skyblue'}]}/>
                <View style={[styles.hw50,{backgroundColor:'steelblue'}]}/>
            </View>
            <View style={{height:20}}/>
            <View style={{
                height:100,
                flexDirection:'row-reverse',
                justifyContent:'flex-end',
                alignItems:'center',
                backgroundColor:'#878787'
            }}>
                <View style={[styles.hw50,{backgroundColor:'#0bffd3'}]}/>
                <View style={[styles.hw50,{backgroundColor:'powderblue'}]}/>
                <View style={[styles.hw50,{backgroundColor:'skyblue'}]}/>
                <View style={[styles.hw50,{backgroundColor:'steelblue'}]}/>
            </View>
  1. Justify Content
    componentstyle属性中添加justifyContent属性是确定子控件在布局坐标轴主轴上的布局方式是哪个。可以选属性值有六个。需要特别注意的是,这个属性作用于所有子控件,即需要将所有子控件作为一个整体来看

    1. flex-start沿着主轴起始方向布局,等同于 Android RelativeLayout中的layout_alignParentStart,即当flex:row时,等同于layout_alignParentLeft,当flex:column时,等同于layout_alignParentTop;
    2. flex-end沿着主轴尾部方向布局,等同于 Android RelativeLayout中的layout_alignParentEnd,即当flex:row时,等同于layout_alignParentRight,当flex:column时,等同于layout_alignParentBottom;
    3. center沿着主轴整体居中排列;
    4. space-around`沿着主轴居中、分散排列,即将宽度或者高度均分为子控件数量的小块,在每个小块内,居中展示子控件。
    5. space-betweenspace-evenly类似space-around,但是展示方式略有不同。下面图片的顺序分别是space-around->space-between->space-evenly,主轴为x轴(flexDirection:'row'
      两者对比图
  2. Align Items
    componentstyle属性中添加alignItems属性是确定子控件在坐标轴副轴上的展示关系,主要属性有flex-start``center``flex-endstreth

    1. 需要注意的是,设置streth属性,需要保证副轴上的尺寸不允许有具体数值,否则不会有效果
    2. flex-start``center``flex-end这三个属性值与justifyContent使用方式一致,只不过作用轴相反

下图分别是flexDirectionjustifyContentalignItems三个布局属性相互影响的结果。
enter image description here

布局代码如下(按照图片中布局顺序)
主轴是x轴,即按照水平排列子控件,受到属性justifyContent的值的影响;副轴是y轴,受到属性alignItems的值的影响。

<View style={{
                height:100,
                flexDirection:'row',
                justifyContent:'flex-end',
                alignItems:'flex-end',
                backgroundColor:'#878787'
            }}>
<View style={{
                height:100,
                flexDirection:'row',
                justifyContent:'flex-start',
                alignItems:'flex-end',
                backgroundColor:'#878787'
            }}>
<View style={{
                height:100,
                flexDirection:'row',
                justifyContent:'center',
                alignItems:'flex-start',
                backgroundColor:'#878787'
            }}>

stretch属性值表示拉伸的意思,即在副轴方向上根据父控件在副轴上的尺寸对子控件进行拉伸。

  1. AlignSelf
    componentstyle属性中添加alignSelf属性可以覆盖父控件的style中的alignItems在当前控件上的作用效果,即重新确定当前的控件在父控件中副轴上的位置。
    enter image description here
    布局代码如下
<View style={{
                height:100,
                flexDirection:'row',
                justifyContent:'flex-end',
                alignItems:'flex-end',
                backgroundColor:'#878787'
            }}>
                <View style={[styles.hw50,{backgroundColor:'#0bffd3'},{alignSelf:'center'}]}/>
                <View style={[styles.hw50,{backgroundColor:'powderblue'},{alignSelf:'flex-start'}]}/>
                <View style={[styles.hw50,{backgroundColor:'skyblue'}]}/>
                <View style={[styles.hw50,{backgroundColor:'steelblue'}]}/>
            </View>
  1. padding paddingLeft paddingTop paddingRight paddingBottom,值都是number类型,类比 Android 中的 padding paddingLeft paddingTop paddingRight paddingBottom
  2. margin marginLeft marginTop marginRight marginBottom同上,类比 Android 中的相关属性及用法。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值