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閱讀 228,412評論 6 532
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,514評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,373評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,975評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,743評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,199評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,262評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,414評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,951評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,780評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,983評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,527評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,218評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,649評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,889評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,673評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,967評論 2 374

推薦閱讀更多精彩內容

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