react native學(xué)習(xí)筆記3——常見的基本組件簡介

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

Demo代碼的使用

相關(guān)的Demo代碼可以在https://github.com/mronion0603/ReactNativeExercise下載,或者直接復(fù)制到你的工程里使用即可。
Demo的示例代碼結(jié)構(gòu)

├── 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時最基礎(chǔ)的組件,View通常用作容器,它可以放到其它的視圖里,也可以有任意多個任意類型的子視圖,支持Flexbox布局。View類似IOS中的UIView,Android中的android.view.View。

下面的例子創(chuàng)建了一個View,包含了三個有顏色的方塊,并且設(shè)置了一個內(nèi)邊距:

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

效果圖如下:

如果內(nèi)部Text組件沒有定義自己的樣式,那么內(nèi)部Text組件會繼承外部組件的樣式,哪一項自己沒有定義,就會繼承哪一項。

<Text>元素在布局上不同于其它組件:在Text內(nèi)部的元素不再使用flexbox布局,而是采用文本布局。這意味著<Text>內(nèi)部的元素不再是一個個矩形,而可能會在行末進(jìn)行折疊。

3.TextInput

文本框輸入組件,它有一個名為onChangeText的屬性,此屬性接受一個函數(shù),而此函數(shù)會在文本變化時被調(diào)用。另外還有一個名為onSubmitEditing的屬性,會在文本被提交后(用戶按下軟鍵盤上的提交鍵)調(diào)用。

假如我們要實現(xiàn)當(dāng)用戶輸入時,實時將其以單詞為單位翻譯為另一種文字。我們假設(shè)這另一種文字來自某個吃貨星球,只有一個單詞: ??。所以"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)絡(luò)圖片、靜態(tài)資源、臨時的本地圖片、以及本地磁盤上的圖片(如相冊)等。

靜態(tài)圖片資源

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

使用混合App的圖片資源

如果你在編寫一個混合App(一部分UI使用React Native,而另一部分使用平臺原生代碼),也可以使用已經(jīng)打包到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}} />

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

網(wǎng)絡(luò)圖片

很多要在App中顯示的圖片并不能在編譯的時候獲得,又或者有時候需要動態(tài)載入來減少打包后的二進(jìn)制文件的大小。這些時候,與靜態(tài)資源不同的是,你需要手動指定圖片的尺寸
。同時我們強(qiáng)烈建議你使用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)圖片資源時可以不用設(shè)置寬高,使用網(wǎng)絡(luò)圖片需要手動指定圖片的尺寸,否則什么都不顯示。

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屬性來設(shè)置)。對應(yīng)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中的所有組件都會被渲染,哪怕有些組件因為內(nèi)容太長被擠出了屏幕外。如果你需要顯示較長的滾動列表,那么應(yīng)該使用功能差不多但性能更好的ListView FlatList組件。

6.FlatList

熟悉客戶端開發(fā)的朋友看到這可能會問,為什么不是ListView, 其實FlatList就是升級版的ListView,F(xiàn)latList 主要是解決 ListView 的性能問題,數(shù)據(jù)量大時 ListView 性能較差,占用內(nèi)存持續(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ù),返回一個設(shè)定好格式的組件來渲染。

完整的例子:

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,并預(yù)設(shè)了一些模擬數(shù)據(jù)。首先是初始化FlatList所需的data,其中的每一項(行)數(shù)據(jù)之后都在renderItem中被渲染成了Text組件,最后構(gòu)成整個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,
    },
})

效果圖如下:

相關(guān)的Demo代碼可以在https://github.com/mronion0603/ReactNativeExercise下載

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,455評論 25 708
  • afinalAfinal是一個android的ioc,orm框架 https://github.com/yangf...
    passiontim閱讀 15,568評論 2 45
  • 少壯風(fēng)雨幾溝壑, 破釜沉舟回音樂。 絕壁陡崖蝴蝶舞, 獨載后海問天國。
    良仁學(xué)子閱讀 182評論 1 1
  • 18/30#寫手圈連續(xù)寫作訓(xùn)練營# 【讀書】 【讀書感悟】 【寫作】《1910(第5節(jié))》 作者:白鼠 撲倒在中年...
    作家白鼠閱讀 349評論 0 0
  • 前兩天我們談到了為什么寫作,如何寫作,今天我們談?wù)剬懽鞯牡讓舆壿嫛饕怯^點傳播類的邏輯。 你需要知道的一個概念...
    007歡閱讀 467評論 0 2