#3 RN 基础知识

本文来自React Native中文网, 个人初学笔记

主要包含:

  1. AppRegistry 及 注册组件是注意的问题
  2. 样式的写法,StyleSheet, StyleSheet.create
  3. 宽高 width, height, flexbox布局
  4. TextInput | ScrollView | ListView 等RN组件初步使用
  5. Navigator 进行路由切换场景

AppRegistry

这个模块告诉React Native(简称RN)哪一个组件被注册为整个应用的根容器。一般整个应用里面 AppRegistry.registerComponent方法只会调用一次

import { AppRegistry, Text } from 'react-native'

// HelloWorld 组件

AppRegistry.registerComponent(
  'HelloWorld', 
  () => HelloWorld
)

注意 项目名 和 注册组件不匹配的情况

比如我的项目为:

react-native init AwesomeApp

但是在index.android.js中注册了其它的组件 Bananas:

import React, { Component } from 'react';
import { AppRegistry, Image, Text, View } from 'react-native';

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

index.android.js 中写成了:

AppRegistry.registerComponent('Bananas', () => Bananas)

这个时候会出现 react-native application has not been registered 错误,

我们应该在index.android.js中写为:

AppRegistry.registerComponent('AwesomeApp', () => Bananas);

具体 组件未注册

样式 StyleSheet

RN中样式采用驼峰命名法, 比如'background-color' 写为 'backgroundColor'

可以通过引入 StyleSheet, 通过 StyleSheet.create 来几种定义组件的样式

import { StyleSheet, Text, View } from 'react-native';

class LotsOfStyles extends Component {
  render() {
    return (
      <View>
        <Text style={styles.redText}>just red</Text>
      </View>
    )
  }
}

# 集中定义样式
const styles = StyleSheet.create({
    redText: {
      fontSize: 30,  // 注意这里没有单位
      color: 'red',
      fontWeight: 'bold',
    }
})

当然我们也可以通过style,直接添加样式,也是采用驼峰法

<Text style={{color: 'red', fontSize: 20}}>Hello</Text>

宽高 width && height

RN 中的尺寸都是无单位的, 表示的是与设备像素密度无关的逻辑像素点

给组件设置尺寸最简单的是指定固定的 width height。这是比较常见的模式,比如不同的尺寸屏幕显示固定的大小

class FixedDimensionsBasics extends Component {
  render() {
    return (
      <View>
        <View style={{ width: 50, height: 100, backgroundColor: 'skyblue'}} />
      </View>
    )
  }
}

弹性宽高(flex)

可以使用 flex 动态的扩展或缩放。

flex: 1 常用来指定某个组件扩张以撑满剩余的空间, flex值的大小决定,扩张剩余空间的比例大小

组件能扩张或缩放的前提是:父容器尺寸不为0。如果父容器既没有固定width和height,也没有设定 flex 的值,则父容器尺寸将为0,其子组件如果使用了flex,也无法显示

class FlexDimensionsBasics extends Component {
  render() {
    return (
      <View style={{ flex: 1 }}>
        <View style={{ flex: 1, backgroundColor: 'skyblue'}} />
        <View style={{ flex: 2, backgroundColor: 'yellow'}} />
        <View style={{ flex: 3, backgroundColor: 'red'}} />
      </View>
    )
  }
}
# 这种情况, 3个子View将按照 '1:2:3' 的比例分割 父容器。

如果不指定 flex 和 height:

<View>
  <View style={{ flex: 1, backgroundColor: 'skyblue'}} />
  <View style={{ flex: 2, backgroundColor: 'yellow'}} />
  <View style={{ flex: 3, backgroundColor: 'red'}} />
</View>
# 这种情况, 不会显示任何东西

指定 height

<View style={{height: 300}}>
  <View style={{ flex: 1, backgroundColor: 'skyblue'}} />
  <View style={{ flex: 2, backgroundColor: 'yellow'}} />
  <View style={{ flex: 3, backgroundColor: 'red'}} />
</View>
# 这种情况, 3个子View将按照 '1:2:3' 的比例分割 父容器300的高

Flexbox

这个属性和web CSS中基本差不多,RN中使用 flexDirection | alignItems | justifyContent | flex等,以下是差异点:

  • RN中 flexDirection 默认值是 column 而不是 row
  • RN中 flex 只能指定一个数字值, 而不是web css 中的3个值

其余的基本相似

<View style={{ 
    flex: 1, 
    flexDirection: 'row', 
    justifyContent: 'space-around',
    alignItems: 'center'
}}>
  <View style={{ width: 50, height: 50, backgroundColor: 'pink' }} />
  <View style={{ width: 50, height: 50, backgroundColor: '#34d' }} /
  <View style={{ width: 50, height: 50, backgroundColor: '#fa1' }} />
</View>

TextInput

允许用户输入文本的基础组件

属性:

  • onChangeText: 相当于 React中的 onChange 事件,当文本变化时被调用
  • onSubmitEditing: 当文本被提交(用户调用软键盘的提交键)时调用

比如:

# text 为一个状态, 默认为''

<View style={{padding: 10}}>
    <TextInput
      style={{height: 40}}
      placeholder="Type here to translate!"
      onChangeText={(text) => this.setState({text})}
    />
    <Text style={{padding: 10, fontSize: 42}}>
      {this.state.text.split(' ').map((word) => word && '🍕').join(' ')}
    </Text>
  </View>

ScrollView

一个通用的可滚动的容器。可以在其中放多个组件和视图,这些组件可以不是同类型。ScrollView 还可以水平滚动 (通过设置 horizontal 属性)

ScrollView 适合用来显示数量不多的滚动元素, 如果需要显示较长的滚动列表,可以使用功能类似,性能更好的ListView

import { ScrollView } from 'react-native';

<ScrollView>
  <Text style={{fontSize: 40, color: "green"}}>滚动吧</Text>
  <Image source={require('./imgs/1.jpg')} style={width: 100, height: 100} />
  // ...
<ScrollView>

ListView

显示垂直滚动列表,元素之间的结构近似而仅数据不同,更适合于长列表数据,且元素个数可增删。常用于从服务端取回列表数据然后显示。类似于 ul > li

ListView特点:

  • 和ScrollList不同的是, ListView 并不立即渲染所有元素,而是优先渲染屏幕上的可见的元素。
  • ListView组件必须有3个属性: dataSource(列表数据源), renderRow(逐个解析数据源中的数据, 然后返回一个设定好的格式), rowHasChanged(函数)

示例:

class ListViewBasics extends Component {
  constructor(props) {
    // 初始化模拟数据
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows([
        'Kobe', 'Jordan', 'Durant', 'James'
      ])
    };
  }
  render() {
    return (
      <View style={{flex: 1, paddingTop: 22}}>
        <ListView 
          dataSource={this.state.dataSource}
          renderRow={(rowData) => <Text>{rowData}</Text>}
        />
      </View>
    );
  }
}

Navigator

这个是导航器组件,利用 场景(Scene) 的概念

属性:

  • initialRoute: 初始路由
  • renderScence: 渲染场景,这里面接一个函数(route, navigator) => MyScene

场景的推入导航栈

上面 renderScence 中有 navigator 作为参数,可以使用下面方法进行前进或后退

// 进入导航栈
navigator.push({
  title: 'Next Scene',
  index: 1,
})

navigator.pop() // 出导航栈

完整示例:

import React, {Component} from 'react'
import {AppRegistry, Navigator, TouchableHighlight, Text, View}
from 'react-native'

class MyScene extends Component {
  render() {
    return (
      <View>
        <Text>Current Scene: { this.props.title }</Text>
        <TouchableHighlight onPress={this.props.onForward}>
          <Text>点我进入下一场景</Text>
        </TouchableHighlight>
        <TouchableHighlight onPress={this.props.onBack}>
          <Text>点我返回上一场景</Text>
        </TouchableHighlight>    
      </View>
    )
  }
}

class SimpleNavigationApp extends Component {
  render() {
    return (
      <Navigator            
        initialRoute={{title: 'My Initial Scene', index: 0}}
        # 此处的route会使用上面的initialRoute作为初始值
        renderScene={(route, navigator) =>  
          <MyScene 
            title={route.title}
            # 前进
            onForward={ () => {
              const nextIndex = route.index + 1,
              navigator.push({
                title: 'Scene ' + nextIndex,
                index: nextIndex
              });
            }}
            # 后退
            onBack={() => {
              if (route.index > 0) {
                navigator.pop();
              }
            }}
          />
        }
      />
    )
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容