本文是我整理的各個(gè)常用組件的基本使用方法,主要簡(jiǎn)要幾個(gè)常見(jiàn)的基本組件,作為入門材料使初學(xué)者對(duì)RN中的常用組件有個(gè)直觀的了解,快速入門,加強(qiáng)學(xué)習(xí)的成就感,增強(qiáng)學(xué)習(xí)RN的動(dòng)力,不會(huì)面面俱到的詳細(xì)講解組件中的各個(gè)屬性的含義及用法,如需深入了解可以查看官網(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
在根目錄下新建了一個(gè)App.js文件,在index.android.js和index.ios.js中分別都import './App';所以不論你是運(yùn)行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時(shí)最基礎(chǔ)的組件,View通常用作容器,它可以放到其它的視圖里,也可以有任意多個(gè)任意類型的子視圖,支持Flexbox布局。View類似IOS中的UIView,Android中的android.view.View。
下面的例子創(chuàng)建了一個(gè)View,包含了三個(gè)有顏色的方塊,并且設(shè)置了一個(gè)內(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
一個(gè)專門用于顯示文本的基本組件,類似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組件沒(méi)有定義自己的樣式,那么內(nèi)部Text組件會(huì)繼承外部組件的樣式,哪一項(xiàng)自己沒(méi)有定義,就會(huì)繼承哪一項(xiàng)。
<Text>元素在布局上不同于其它組件:在Text內(nèi)部的元素不再使用flexbox布局,而是采用文本布局。這意味著<Text>內(nèi)部的元素不再是一個(gè)個(gè)矩形,而可能會(huì)在行末進(jìn)行折疊。
3.TextInput
文本框輸入組件,它有一個(gè)名為onChangeText的屬性,此屬性接受一個(gè)函數(shù),而此函數(shù)會(huì)在文本變化時(shí)被調(diào)用。另外還有一個(gè)名為onSubmitEditing的屬性,會(huì)在文本被提交后(用戶按下軟鍵盤上的提交鍵)調(diào)用。
假如我們要實(shí)現(xiàn)當(dāng)用戶輸入時(shí),實(shí)時(shí)將其以單詞為單位翻譯為另一種文字。我們假設(shè)這另一種文字來(lái)自某個(gè)吃貨星球,只有一個(gè)單詞: ??。所以"Hello there Bob"將會(huì)被翻譯為"??????"。
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
一個(gè)用于顯示多種不同類型圖片的組件,包括網(wǎng)絡(luò)圖片、靜態(tài)資源、臨時(shí)的本地圖片、以及本地磁盤上的圖片(如相冊(cè))等。
靜態(tài)圖片資源
<Image source={require('./my-icon.png')} />
使用混合App的圖片資源
如果你在編寫一個(gè)混合App(一部分UI使用React Native,而另一部分使用平臺(tái)原生代碼),也可以使用已經(jīng)打包到App中的圖片資源(以拖拽的方式放置在Xcode的asset類目中,或是放置在Android的drawable目錄里)。注意此時(shí)只使用文件名,不帶路徑也不帶后綴:
<Image source={{uri: 'app_icon'}} style={{width: 40, height: 40}} />
對(duì)于放置在Android的assets目錄中的圖片,還可以使用asset:/ 前綴來(lái)引用:
<Image source={{uri: 'asset:/app_icon.png'}} style={{width: 40, height: 40}} />
注意:這一做法并沒(méi)有任何安全檢查。你需要自己確保圖片在應(yīng)用中確實(shí)存在,而且還需要指定尺寸。
網(wǎng)絡(luò)圖片
很多要在App中顯示的圖片并不能在編譯的時(shí)候獲得,又或者有時(shí)候需要?jiǎng)討B(tài)載入來(lái)減少打包后的二進(jìn)制文件的大小。這些時(shí)候,與靜態(tài)資源不同的是,你需要手動(dòng)指定圖片的尺寸
。同時(shí)我們強(qiáng)烈建議你使用https以滿足iOS App Transport Security 的要求。
// 正確
<Image source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} style={{width: 400, height: 400}} />
// 錯(cuò)誤
<Image source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} />
注意:使用靜態(tài)圖片資源時(shí)可以不用設(shè)置寬高,使用網(wǎng)絡(luò)圖片需要手動(dòng)指定圖片的尺寸,否則什么都不顯示。
ImageBackground
ImageBackground是背景圖片組件,是在rn 0.46版本加入的,它的用法類似Image,只不過(guò)可以嵌套其他組件
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是一個(gè)通用的可滾動(dòng)的容器,它可以嵌入多個(gè)組件和視圖,而且這些組件并不需要是同類型的。ScrollView不僅可以垂直滾動(dòng),還能水平滾動(dòng)(通過(guò)horizontal屬性來(lái)設(shè)置)。對(duì)應(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適合用來(lái)顯示數(shù)量不多的滾動(dòng)元素。放置在ScollView中的所有組件都會(huì)被渲染,哪怕有些組件因?yàn)閮?nèi)容太長(zhǎng)被擠出了屏幕外。如果你需要顯示較長(zhǎng)的滾動(dòng)列表,那么應(yīng)該使用功能差不多但性能更好的
ListViewFlatList組件。
6.FlatList
熟悉客戶端開(kāi)發(fā)的朋友看到這可能會(huì)問(wèn),為什么不是ListView, 其實(shí)FlatList就是升級(jí)版的ListView,F(xiàn)latList 主要是解決 ListView 的性能問(wèn)題,數(shù)據(jù)量大時(shí) ListView 性能較差,占用內(nèi)存持續(xù)增加。官方在0.43版本加入了FlatList,并逐漸廢棄Listview。
FlatList是高性能的簡(jiǎn)單列表組件,適用于展示長(zhǎng)列表數(shù)據(jù),和ScrollView
不同的是,F(xiàn)latList并不立即渲染所有元素,而是優(yōu)先渲染屏幕上可見(jiàn)的元素。
一個(gè)簡(jiǎn)單的例子:
<FlatList
data={[{key: 'a'}, {key: 'b'}]}
renderItem={({item}) => <Text>{item.key}</Text>}
/>
data和renderItem是FlatList所必須的兩個(gè)屬性:
- data :列表的數(shù)據(jù)源
- renderItem :從數(shù)據(jù)源中逐個(gè)解析數(shù)據(jù),返回一個(gè)設(shè)定好格式的組件來(lái)渲染。
完整的例子:
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)建了一個(gè)簡(jiǎn)單的FlatList,并預(yù)設(shè)了一些模擬數(shù)據(jù)。首先是初始化FlatList所需的data,其中的每一項(xiàng)(行)數(shù)據(jù)之后都在renderItem中被渲染成了Text組件,最后構(gòu)成整個(gè)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: ...},
]}
/>
一個(gè)簡(jiǎn)單的例子:
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下載