本文是我整理的各個常用組件的基本使用方法差牛,主要簡要幾個常見的基本組件,作為入門材料使初學者對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.js
和index.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中的所有組件都會被渲染病涨,哪怕有些組件因為內容太長被擠出了屏幕外富玷。如果你需要顯示較長的滾動列表,那么應該使用功能差不多但性能更好的
ListViewFlatList組件既穆。
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下載