react native學習筆記3——常見的基本組件簡介

本文是我整理的各個常用組件的基本使用方法差牛,主要簡要幾個常見的基本組件,作為入門材料使初學者對RN中的常用組件有個直觀的了解蒜绽,快速入門舟肉,加強學習的成就感,增強學習RN的動力燕酷,不會面面俱到的詳細講解組件中的各個屬性的含義及用法籍凝,如需深入了解可以查看官網(wǎng)文檔

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

作為創(chuàng)建UI時最基礎的組件,View通常用作容器灶挟,它可以放到其它的視圖里琉朽,也可以有任意多個任意類型的子視圖,支持Flexbox布局稚铣。View類似IOS中的UIView箱叁,Android中的android.view.View墅垮。

下面的例子創(chuàng)建了一個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的屬性炭庙,此屬性接受一個函數(shù),而此函數(shù)會在文本變化時被調用煌寇。另外還有一個名為onSubmitEditing的屬性焕蹄,會在文本被提交后(用戶按下軟鍵盤上的提交鍵)調用。

假如我們要實現(xiàn)當用戶輸入時阀溶,實時將其以單詞為單位翻譯為另一種文字腻脏。我們假設這另一種文字來自某個吃貨星球,只有一個單詞: ??银锻。所以"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

一個用于顯示多種不同類型圖片的組件,包括網(wǎng)絡圖片击纬、靜態(tài)資源鼎姐、臨時的本地圖片、以及本地磁盤上的圖片(如相冊)等更振。

靜態(tài)圖片資源

<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}} />

注意:這一做法并沒有任何安全檢查遵蚜。你需要自己確保圖片在應用中確實存在帖池,而且還需要指定尺寸。

網(wǎng)絡圖片

很多要在App中顯示的圖片并不能在編譯的時候獲得吭净,又或者有時候需要動態(tài)載入來減少打包后的二進制文件的大小睡汹。這些時候,與靜態(tài)資源不同的是寂殉,你需要手動指定圖片的尺寸
囚巴。同時我們強烈建議你使用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'}} />

注意:使用靜態(tài)圖片資源時可以不用設置寬高友扰,使用網(wǎng)絡圖片需要手動指定圖片的尺寸彤叉,否則什么都不顯示。

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適合用來顯示數(shù)量不多的滾動元素。放置在ScollView中的所有組件都會被渲染病涨,哪怕有些組件因為內容太長被擠出了屏幕外富玷。如果你需要顯示較長的滾動列表,那么應該使用功能差不多但性能更好的ListView FlatList組件既穆。

6.FlatList

熟悉客戶端開發(fā)的朋友看到這可能會問凌彬,為什么不是ListView, 其實FlatList就是升級版的ListView,F(xiàn)latList 主要是解決 ListView 的性能問題循衰,數(shù)據(jù)量大時 ListView 性能較差铲敛,占用內存持續(xù)增加。官方在0.43版本加入了FlatList会钝,并逐漸廢棄Listview伐蒋。
FlatList是高性能的簡單列表組件,適用于展示長列表數(shù)據(jù)迁酸,和ScrollView
不同的是先鱼,F(xiàn)latList并不立即渲染所有元素,而是優(yōu)先渲染屏幕上可見的元素奸鬓。
一個簡單的例子:

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

data和renderItem是FlatList所必須的兩個屬性:

  • data :列表的數(shù)據(jù)源
  • renderItem :從數(shù)據(jù)源中逐個解析數(shù)據(jù)焙畔,返回一個設定好格式的組件來渲染。

完整的例子:

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,
    },
})

該示例創(chuàng)建了一個簡單的FlatList串远,并預設了一些模擬數(shù)據(jù)宏多。首先是初始化FlatList所需的data儿惫,其中的每一項(行)數(shù)據(jù)之后都在renderItem中被渲染成了Text組件,最后構成整個FlatList伸但。
效果圖如下:

如果需要分組/類/區(qū)(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下載

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末铛铁,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子却妨,更是在濱河造成了極大的恐慌饵逐,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,919評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件彪标,死亡現(xiàn)場離奇詭異梳毙,居然都是意外死亡,警方通過查閱死者的電腦和手機捐下,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,567評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來萌业,“玉大人坷襟,你說我怎么就攤上這事∩辏” “怎么了婴程?”我有些...
    開封第一講書人閱讀 163,316評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長抱婉。 經常有香客問我档叔,道長,這世上最難降的妖魔是什么蒸绩? 我笑而不...
    開封第一講書人閱讀 58,294評論 1 292
  • 正文 為了忘掉前任衙四,我火速辦了婚禮,結果婚禮上患亿,老公的妹妹穿的比我還像新娘传蹈。我一直安慰自己,他們只是感情好步藕,可當我...
    茶點故事閱讀 67,318評論 6 390
  • 文/花漫 我一把揭開白布惦界。 她就那樣靜靜地躺著,像睡著了一般咙冗。 火紅的嫁衣襯著肌膚如雪沾歪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,245評論 1 299
  • 那天雾消,我揣著相機與錄音灾搏,去河邊找鬼挫望。 笑死,一個胖子當著我的面吹牛确镊,可吹牛的內容都是我干的士骤。 我是一名探鬼主播,決...
    沈念sama閱讀 40,120評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼蕾域,長吁一口氣:“原來是場噩夢啊……” “哼拷肌!你這毒婦竟也來了?” 一聲冷哼從身側響起旨巷,我...
    開封第一講書人閱讀 38,964評論 0 275
  • 序言:老撾萬榮一對情侶失蹤巨缘,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后采呐,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體若锁,經...
    沈念sama閱讀 45,376評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,592評論 2 333
  • 正文 我和宋清朗相戀三年斧吐,在試婚紗的時候發(fā)現(xiàn)自己被綠了又固。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,764評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡煤率,死狀恐怖仰冠,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情蝶糯,我是刑警寧澤洋只,帶...
    沈念sama閱讀 35,460評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站昼捍,受9級特大地震影響识虚,放射性物質發(fā)生泄漏。R本人自食惡果不足惜妒茬,卻給世界環(huán)境...
    茶點故事閱讀 41,070評論 3 327
  • 文/蒙蒙 一担锤、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧乍钻,春花似錦妻献、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,697評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至欢摄,卻和暖如春熬丧,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背怀挠。 一陣腳步聲響...
    開封第一講書人閱讀 32,846評論 1 269
  • 我被黑心中介騙來泰國打工析蝴, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留害捕,地道東北人。 一個月前我還...
    沈念sama閱讀 47,819評論 2 370
  • 正文 我出身青樓闷畸,卻偏偏與公主長得像尝盼,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子佑菩,可洞房花燭夜當晚...
    茶點故事閱讀 44,665評論 2 354

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,088評論 25 707
  • afinalAfinal是一個android的ioc盾沫,orm框架 https://github.com/yangf...
    passiontim閱讀 15,429評論 2 45
  • 少壯風雨幾溝壑, 破釜沉舟回音樂殿漠。 絕壁陡崖蝴蝶舞赴精, 獨載后海問天國。
    良仁學子閱讀 179評論 1 1
  • 18/30#寫手圈連續(xù)寫作訓練營# 【讀書】 【讀書感悟】 【寫作】《1910(第5節(jié))》 作者:白鼠 撲倒在中年...
    作家白鼠閱讀 332評論 0 0
  • 前兩天我們談到了為什么寫作绞幌,如何寫作蕾哟,今天我們談談寫作的底層邏輯——主要是觀點傳播類的邏輯。 你需要知道的一個概念...
    007歡閱讀 455評論 0 2