react native学习笔记3——常见的基本组件简介

本文是我整理的各个常用组件的基本使用方法,主要简要几个常见的基本组件,作为入门材料使初学者对RN中的常用组件有个直观的了解,快速入门,加强学习的成就感,增强学习RN的动力,不会面面俱到的详细讲解组件中的各个属性的含义及用法,如需深入了解可以查看官网文档

Demo代码的使用

相关的Demo代码可以在https://github.com/mronion0603/ReactNativeExercise下载,或者直接复制到你的工程里使用即可。
Demo的示例代码结构

├── index.android.js
└── index.ios.js
└── App.js
└── src
         ├── 01_componts
         └── images

在根目录下新建了一个App.js文件,在index.android.jsindex.ios.js中分别都import './App';所以不论你是运行Android还是IOS都可以只在./App中import你要尝试的组件代码,然后替换render中的组件。组件示例代码在src/01_componts文件夹中,图片资源在src/images中。
例如:App.js

import React, { Component } from 'react';
import {
    AppRegistry,
} from 'react-native';
import SectionListDemo from "./src/01_componts/SectionListDemo";
import FlatListDemo from "./src/01_componts/FlatListDemo";
import ScrollViewDemo from "./src/01_componts/ScrollViewDemo";
import TextinputDemo from "./src/01_componts/TextinputDemo";
import ImageDemo from "./src/01_componts/ImageDemo";
import ViewDemo from "./src/01_componts/ViewDemo";
import TextDemo from "./src/01_componts/TextDemo";
import CompontsTest from "./src/01_componts/CompontsTest";
export default class ExerciseProject extends Component {
    render() {
        return (
            <ViewDemo />
        );
    }
}
AppRegistry.registerComponent('ExerciseProject', () => ExerciseProject);

若想看看TextDemo 的效果,可以直接将<ViewDemo />替换为<TextDemo />

1.View

作为创建UI时最基础的组件,View通常用作容器,它可以放到其它的视图里,也可以有任意多个任意类型的子视图,支持Flexbox布局。View类似IOS中的UIView,Android中的android.view.View。

下面的例子创建了一个View,包含了三个有颜色的方块,并且设置了一个内边距:

import React, {Component} from "react";
import {View} from "react-native";

export default class CompontsTest extends Component {
    render() {
        return (
            <View style={{ backgroundColor: "#fff", flex: 1, padding: 20}}>
                <View style={{flex: 1,flexDirection:"row", backgroundColor: 'powderblue'}}/>
                <View style={{flex: 2, backgroundColor: 'skyblue'}} />
                <View style={{flex: 3, backgroundColor: 'steelblue'}} />
            </View>
        )
    }
}

效果图如下:

2.Text

一个专门用于显示文本的基本组件,类似IOS中的UILabel与Android中的TextView。并且它也支持嵌套、样式,以及触摸处理。

import React, {Component} from "react";
import {View,Text,StyleSheet,} from "react-native";

export default class CompontsTest extends Component {
    render() {
        return (
            <Text style={styles.outerText}>I am outerText!
                <Text style={styles.innerText}>I am innerText!
                </Text>
            </Text>
        )
    }
}

const styles = StyleSheet.create({
    outerText:{
        textAlign:'center',
        color:'red',
        fontSize:28,
        fontFamily:'Cochin'
    },
    innerText: {
        color:'green',
        fontWeight:'bold',
    },
});

效果图如下:

如果内部Text组件没有定义自己的样式,那么内部Text组件会继承外部组件的样式,哪一项自己没有定义,就会继承哪一项。

<Text>元素在布局上不同于其它组件:在Text内部的元素不再使用flexbox布局,而是采用文本布局。这意味着<Text>内部的元素不再是一个个矩形,而可能会在行末进行折叠。

3.TextInput

文本框输入组件,它有一个名为onChangeText的属性,此属性接受一个函数,而此函数会在文本变化时被调用。另外还有一个名为onSubmitEditing的属性,会在文本被提交后(用户按下软键盘上的提交键)调用。

假如我们要实现当用户输入时,实时将其以单词为单位翻译为另一种文字。我们假设这另一种文字来自某个吃货星球,只有一个单词: 🍕。所以"Hello there Bob"将会被翻译为"🍕🍕🍕"。

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

export default class TextinputDemo extends Component {
    constructor(props) {
        super(props);
        this.state = {text: ''};
    }

    render() {
        return (
            <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>
        );
    }
}

效果图如下:

4.Image

一个用于显示多种不同类型图片的组件,包括网络图片、静态资源、临时的本地图片、以及本地磁盘上的图片(如相册)等。

静态图片资源

<Image source={require('./my-icon.png')} />

使用混合App的图片资源

如果你在编写一个混合App(一部分UI使用React Native,而另一部分使用平台原生代码),也可以使用已经打包到App中的图片资源(以拖拽的方式放置在Xcode的asset类目中,或是放置在Android的drawable目录里)。注意此时只使用文件名,不带路径也不带后缀:

<Image source={{uri: 'app_icon'}} style={{width: 40, height: 40}} />

对于放置在Android的assets目录中的图片,还可以使用asset:/ 前缀来引用:

 <Image source={{uri: 'asset:/app_icon.png'}} style={{width: 40, height: 40}} />

注意:这一做法并没有任何安全检查。你需要自己确保图片在应用中确实存在,而且还需要指定尺寸。

网络图片

很多要在App中显示的图片并不能在编译的时候获得,又或者有时候需要动态载入来减少打包后的二进制文件的大小。这些时候,与静态资源不同的是,你需要手动指定图片的尺寸
。同时我们强烈建议你使用https以满足iOS App Transport Security 的要求。

// 正确
<Image source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} style={{width: 400, height: 400}} />
// 错误
<Image source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} />

注意:使用静态图片资源时可以不用设置宽高,使用网络图片需要手动指定图片的尺寸,否则什么都不显示。

ImageBackground

ImageBackground是背景图片组件,是在rn 0.46版本加入的,它的用法类似Image,只不过可以嵌套其他组件

return (
  <ImageBackground style={{height:100,width:300}} source={require('../images/vip_account.png')}>
    <Text>Inside</Text>
  </ImageBackground>
);

代码用法样例

import React, {Component} from "react";
import {StyleSheet,View,Image,ImageBackground,Text} from "react-native";

export default class ImageDemo extends Component {
    render() {
        return (
            <View style={{ backgroundColor: "#fff", flex: 1, padding: 20}}>
                <Image source={require('../images/vip_account.png')} />

                <Image style={ImageDemoStyle.myimage}
                       source={{uri: 'https://manhua.qpic.cn/vertical/0/21_14_21_96ed95f31667b3966cb0e0521ce13703_1498026084112.jpg/420'}}/>

                <ImageBackground style={{ height: 50, width: 50}} source={require('../images/vip_account.png')}>
                    <Text>Inside</Text>
                </ImageBackground>

            </View>
        )
    }
}

const ImageDemoStyle = StyleSheet.create({
    container: {
        backgroundColor: "#fff",
        flex: 1,
        padding: 20
    },
    myimage: {
        height: 70,
        width: 70,
    },
})

效果图如下:

5.ScrollView

ScrollView是一个通用的可滚动的容器,它可以嵌入多个组件和视图,而且这些组件并不需要是同类型的。ScrollView不仅可以垂直滚动,还能水平滚动(通过horizontal属性来设置)。对应Android中的ScrollView,IOS中的UIScrollView。

import React, {Component} from "react";
import {View,ScrollView} from "react-native";

export default class ScrollViewDemo extends Component {
    render() {
        return (
            <ScrollView>
                <Text style={{fontSize:96}}>Scroll me plz</Text>
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Text style={{fontSize:96}}>If you like</Text>
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Text style={{fontSize:96}}>Scrolling down</Text>
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Text style={{fontSize:96}}>What's the best</Text>
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Text style={{fontSize:96}}>Framework around?</Text>
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Image source={require('../images/vip_account.png')} />
                <Text style={{fontSize:80}}>React Native</Text>
            </ScrollView>
        )
    }
}

效果图如下:

ScrollView适合用来显示数量不多的滚动元素。放置在ScollView中的所有组件都会被渲染,哪怕有些组件因为内容太长被挤出了屏幕外。如果你需要显示较长的滚动列表,那么应该使用功能差不多但性能更好的ListView FlatList组件。

6.FlatList

熟悉客户端开发的朋友看到这可能会问,为什么不是ListView, 其实FlatList就是升级版的ListView,FlatList 主要是解决 ListView 的性能问题,数据量大时 ListView 性能较差,占用内存持续增加。官方在0.43版本加入了FlatList,并逐渐废弃Listview。
FlatList是高性能的简单列表组件,适用于展示长列表数据,和ScrollView
不同的是,FlatList并不立即渲染所有元素,而是优先渲染屏幕上可见的元素。
一个简单的例子:

<FlatList
  data={[{key: 'a'}, {key: 'b'}]}
  renderItem={({item}) => <Text>{item.key}</Text>}
/>

data和renderItem是FlatList所必须的两个属性:

  • data :列表的数据源
  • renderItem :从数据源中逐个解析数据,返回一个设定好格式的组件来渲染。

完整的例子:

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

export default class FlatListDemo extends Component {
    render() {
        return (
            <View style={styles.container}>
                <FlatList
                    data={[
                        {key: 'Devin'},
                        {key: 'Jackson'},
                        {key: 'James'},
                        {key: 'Joel'},
                        {key: 'John'},
                        {key: 'Jillian'},
                        {key: 'Jimmy'},
                        {key: 'Julie'},
                    ]}
                    renderItem={({item}) => <Text style={styles.item}>{item.key}</Text>}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        paddingTop: 22
    },
    item: {
        padding: 10,
        fontSize: 18,
        height: 44,
    },
})

该示例创建了一个简单的FlatList,并预设了一些模拟数据。首先是初始化FlatList所需的data,其中的每一项(行)数据之后都在renderItem中被渲染成了Text组件,最后构成整个FlatList。
效果图如下:

如果需要分组/类/区(section),推荐使用SectionList

7.SectionList

SectionList是高性能的分组(section)列表组件,其功能与FlatList类似。
其基本的写法如下:

<SectionList
  renderItem={({item}) => <ListItem title={item.title} />}
  renderSectionHeader={({section}) => <Header title={section.key} />}
  sections={[ // 不同section渲染相同类型的子组件
    {data: [...], title: ...},
    {data: [...], title: ...},
    {data: [...], title: ...},
  ]}
/>

<SectionList
  sections={[ // 不同section渲染不同类型的子组件
    {data: [...], renderItem: ...},
    {data: [...], renderItem: ...},
    {data: [...], renderItem: ...},
  ]}
/>

一个简单的例子:

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

export default class SectionListDemo extends Component {
    render() {
        return (
            <View style={styles.container}>
                <SectionList
                    sections={[
                        {title: 'B', data: ['Bob','Bla','Boss']},
                        {title: 'D', data: ['Devin','Dave','Dollor']},
                        {title: 'J', data: ['Jackson', 'James', 'Jillian']},
                    ]}
                    renderItem={({item}) => <Text style={styles.item}>{item}</Text>}
                    renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        paddingTop: 22
    },
    sectionHeader: {
        paddingTop: 2,
        paddingLeft: 10,
        paddingRight: 10,
        paddingBottom: 2,
        fontSize: 14,
        fontWeight: 'bold',
        backgroundColor: 'rgba(247,247,247,1.0)',
    },
    item: {
        padding: 10,
        fontSize: 18,
        height: 44,
    },
})

效果图如下:

相关的Demo代码可以在https://github.com/mronion0603/ReactNativeExercise下载

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,569评论 25 707
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,087评论 2 44
  • 少壮风雨几沟壑, 破釜沉舟回音乐。 绝壁陡崖蝴蝶舞, 独载后海问天国。
    良仁学子阅读 169评论 1 1
  • 18/30#写手圈连续写作训练营# 【读书】 【读书感悟】 【写作】《1910(第5节)》 作者:白鼠 扑倒在中年...
    作家白鼠阅读 308评论 0 0
  • 前两天我们谈到了为什么写作,如何写作,今天我们谈谈写作的底层逻辑——主要是观点传播类的逻辑。 你需要知道的一个概念...
    007欢阅读 426评论 0 2