React-Native中一些常用組件的用法詳解(二)
前言
本文為大家介紹一下React-Native中一些深入些的組件,由于對ES6的語法并沒有完全掌握,這里暫時用ES5和ES6混用的語法。
ScrollView組件
能夠調(diào)用移動平臺的ScrollView(滾動視圖)的組件,同時還集成了觸摸鎖定的“響應(yīng)者”系統(tǒng)。
注意一定要給scrollview一個高度,或者是他父級的高度。
常用方法
- onScrollBeginDrag:開始拖拽的時候;
- onScrollEndDrag:結(jié)束拖拽的時候;
- onMomentumScrollBegin:開始滑動;
- onMomentumScrollEnd:開始滑動;
特殊組件
- RefreshControl 以用在ScrollView或ListView內(nèi)部,為其添加下拉刷新的功能。
- 當(dāng)ScrollView處于豎直方向的起點位置(scrollY: 0),此時下拉會觸發(fā)一個onRefresh事件。
示例
創(chuàng)建一個scroll.js文件
代碼如下:
import React, { Component } from 'react';
import {
StyleSheet,
View,
ScrollView,
RefreshControl
} from 'react-native';
var dataSource = require("./data.json");
// 創(chuàng)建組件
var ScrollTest = React.createClass({
// 下面的幾種函數(shù)可以根據(jù)自己的需求添加
_onScrollBeginDrag () {
// 這里是開始拖拽的函數(shù)
},
_onScrollEndDrag () {
// 這里是拖拽結(jié)束的函數(shù)
},
_onMomentumScrollBegin () {
// 這里是開始滾動的函數(shù)
},
_onMomentumScrollEnd () {
// 這里是滾動結(jié)束的函數(shù)
},
_refresh () {
// 這里是請求數(shù)據(jù)的函數(shù)
alert("正在請求數(shù)據(jù)");
},
render () {
return (
<ScrollView style={styles.container}
onScrollBeginDrag={this._onScrollBeginDrag}
onScrollEndDrag={this._onScrollEndDrag}
onMomentumScrollBegin={this._onMomentumScrollBegin}
onMomentumScrollEnd={this._onMomentumScrollEnd}
refreshControl={
<RefreshControl refreshing={false}
titleColor={"red"}
title={"正在刷新......."}
tintColor={"cyan"}
onRefresh={this._refresh} />
}>
<View style={[styles.item, styles.item1]}></View>
<View style={[styles.item, styles.item2]}></View>
<View style={[styles.item, styles.item3]}></View>
</ScrollView>
)
}
});
// 實例化樣式
var styles = StyleSheet.create({
container: {
marginTop: 25,
height: 300,
borderWidth: 1,
borderColor: "#ccc"
},
item: {
width: 280,
height: 150,
margin: 20
},
item1: {
backgroundColor: "red"
},
item2: {
backgroundColor: "green"
},
item3: {
backgroundColor: "yellow"
}
});
module.exports = ScrollTest;
再將index.ios.js文件改成如下:
import React, { Component } from 'react';
import {
AppRegistry,
View,
} from 'react-native';
var Scroll = require("./scroll");
var ScrollTest = React.createClass({
render () {
return (
<View>
<Scroll></Scroll>
</View>
)
}
});
AppRegistry.registerComponent('useComponent', () => ScrollTest);
最終效果:

ListView組件
用于高效地顯示一個可以垂直滾動的變化的數(shù)據(jù)列表。
最基本的使用方式就是創(chuàng)建一個ListView.DataSource數(shù)據(jù)源,然后給它傳遞一個普通的數(shù)據(jù)數(shù)組,再使用數(shù)據(jù)源來實例化一個ListView組件,并且定義它的renderRow回調(diào)函數(shù),這個函數(shù)會接受數(shù)組中的每個數(shù)據(jù)作為參數(shù),返回一個可渲染的組件(作為listview的每一行)。
數(shù)據(jù)處理
ListView.DataSource為ListView組件提供高性能的數(shù)據(jù)處理和訪問。
我們需要調(diào)用方法從原始輸入數(shù)據(jù)中抽取數(shù)據(jù)來創(chuàng)建ListViewDataSource對象,并用其進(jìn)行數(shù)據(jù)變更的比較。
DataSource初始化:
getInitialState:function () {
// 實例化DataSource對象
var ds = new ListView.DataSource({
rowHasChanged:(oldData,newData) => oldData !== newData
});
return {
data:ds.cloneWithRows(news)
}
}
常用屬性
- 設(shè)置數(shù)據(jù)源:dataSource={this.state.dataSource}
- 設(shè)置列表組件:renderRow={this._renderRow}
- 設(shè)置ListView頭部:renderHeader={this._renderHeader}
- 設(shè)置列表項之間的間隔:renderSeparator={this._renderSeparator}
示例 制作一個電影列表
博主先前從貓眼電影里獲取了一些電影介紹的json文件,有興趣的同學(xué)可以去貓眼電影列表獲取一些信息,注意這里需要json格式轉(zhuǎn)換一下!
這里創(chuàng)建一個movieList.js的文件
代碼如下:
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Image,
ListView
} from 'react-native';
// 通過ListView實現(xiàn)電影列表
var movies = require("./data.json").data.movies;
// 創(chuàng)建組件
var ListMovie = React.createClass({
getInitialState () {
var ds = new ListView.DataSource({
rowHasChanged: (oldData, newData) => oldData !== newData
});
return {dataSource: ds.cloneWithRows(movies)}
},
_renderRow (movie) {
return (
<View style={styles.row}>
<Image style={styles.img} source={{uri: movie.img}}/>
<View style={styles.right}>
<Text style={styles.name}>{movie.nm}</Text>
<Text style={styles.dir}>導(dǎo)演:{movie.dir}</Text>
<Text style={styles.dir}>上映時間:{movie.rt}</Text>
</View>
</View>
)
},
_renderHeader () {
return (
<View style={styles.header}>
<Text style={styles.title}>貓眼熱門電影</Text>
<View style={[styles.separator, {width: "100%"}]}></View>
</View>
)
},
_renderSeparator () {
return <View style={styles.separator}></View>
},
render () {
return <ListView style={styles.container}
dataSource={this.state.dataSource}
renderRow={this._renderRow}
renderHeader={this._renderHeader}
renderSeparator={this._renderSeparator}
/>
}
});
// 實例化樣式
var styles = StyleSheet.create({
container: {
marginTop: 25
},
row: {
flexDirection: "row",
alignItems: "center",
padding: 10
},
img: {
width: 78,
height: 128
},
right: {
marginLeft: 15,
flex: 1
},
name: {
fontSize: 20,
fontWeight: "bold",
marginTop: 3,
marginBottom: 10
},
dir: {
fontSize: 15,
marginBottom: 3,
color: "#686868"
},
header: {
height: 44,
alignItems: "center"
},
title: {
fontSize: 25,
fontWeight: "bold",
lineHeight: 44
},
separator: {
height: 1,
backgroundColor: "#ccc"
}
});
module.exports = ListMovie;
再將index.ios.js文件改成如下:
import React, { Component } from 'react';
import {
AppRegistry,
View,
} from 'react-native';
var ListMovie = require("./listMovie");
var Movie = React.createClass({
render () {
return (
<View>
<ListMovie></ListMovie>
</View>
)
}
});
AppRegistry.registerComponent('useComponent', () => Movie);
最終效果:

Navigator組件
使用導(dǎo)航器可以讓你在應(yīng)用的不同場景(頁面)間進(jìn)行切換。其實質(zhì)上類似于HTML里導(dǎo)航條功能。
不過導(dǎo)航器頁面的跳轉(zhuǎn)需要通過路由對象來分辨不同的場景。
利用renderScene方法,導(dǎo)航欄可以根據(jù)指定的路由來渲染場景。
導(dǎo)航器的設(shè)置步驟
第一步:設(shè)置屬性initialRoute:初始化route對象,指定默認(rèn)頁面,也就是啟動app之后所看到的第一個頁面;
第二步:configureScene:配置場景動畫和手勢;
第三步:renderScene;渲染場景,參數(shù)route(第一步創(chuàng)建并設(shè)置的導(dǎo)航器路由對象),navigator(導(dǎo)航器對象)
代碼展示:
<Navigator
initialRoute={rootRoute}
configureScene={(route)=>Navigator.SceneConfigs.PushFromRight}
renderScene={
(route,navigator)=>{
var MySceneComponent = route.component;
console.log(MySceneComponent);
console.log(“aaaa”);
return (
<MySceneComponent route={route} navigator={navigator}/>
)
}
}
/>
示例
創(chuàng)建一個nav.js文件
代碼如下:
/**
* Created by lanou on 17/4/13.
*/
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity,
TextInput
} from 'react-native';
// 在進(jìn)行導(dǎo)航時,需要先構(gòu)成一些頁面,使用Navigator
// 創(chuàng)建組件
var FirstPage = React.createClass({
getInitialState () {
return {text: ""}
},
saveText (text) {
this.setState({text: text})
},
changePage () {
// 把需要傳遞的值,都放在路由的nextPass屬性里
var nextRoute = {
component: SecondPage,
nextPass: {text: this.state.text}
};
this.props.navigator.push(nextRoute);
},
render () {
return (
<View style={[styles.container, {backgroundColor: "cyan"}]}>
<TextInput style={styles.input} placeholder={"請輸入"} onChangeText={this.saveText}/>
<TouchableOpacity onPress={this.changePage} style={styles.btn}>
<Text style={styles.btnText}>跳轉(zhuǎn)到下一頁</Text>
</TouchableOpacity>
</View>
)
}
});
var SecondPage = React.createClass({
changePage () {
this.props.navigator.pop();
},
render () {
return (
<View style={[styles.container, {backgroundColor: "yellowgreen"}]}>
<Text>接收到的數(shù)據(jù)是{this.props.text}</Text>
<TouchableOpacity onPress={this.changePage} style={styles.btn}>
<Text style={styles.btnText}>返回上一頁</Text>
</TouchableOpacity>
</View>
)
}
});
var Nav = React.createClass({
render () {
// 初始路由,首頁
var rootRoute = {
component: FirstPage,
nextPass: {}
};
return (
<Navigator
// 第一步需要進(jìn)行初始路由的設(shè)置
initialRoute={rootRoute}
// 第二步設(shè)置頁面的切換方式
configureScene={(route) => Navigator.SceneConfigs.FloatFromBottom}
// 第三部確定要渲染的場景(頁面)
renderScene={(route, navigator) => {
// 找到要渲染的頁面
var Component = route.component;
// 渲染時,需要把route和Navigator作為屬性傳遞下去,傳遞的值也作為屬性傳遞
// ...route.nextPass把route中的nextPass里的數(shù)據(jù)都傳遞下去
return <Component {...route.nextPass} text={route.nextPass.text} route={route} navigator={navigator} />
}}
/>
)
}
});
// 實例化樣式
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
btn: {
backgroundColor: "#25f30d",
width: 115,
height: 30,
borderRadius: 5,
justifyContent: "center",
alignItems: "center"
},
btnText: {
fontSize: 14,
fontWeight: "bold"
},
input: {
margin: 30,
borderWidth: 1,
borderColor: "#ccc",
height: 30,
backgroundColor: "#77ccb1"
}
});
module.exports = Nav;
在index.ios.js文件中代碼更改如下:
import React, { Component } from 'react';
import {
AppRegistry,
View,
} from 'react-native';
var Nav = require("./nav");
var NavTest = React.createClass({
render () {
return (
<View style={{flex: 1}}>
<Nav></Nav>
</View>
)
}
});
AppRegistry.registerComponent('useComponent', () => NavTest);
最終效果:

TableBarIOS組件
TableBar是放置在屏幕的最下方會有很多平級的標(biāo)簽圖標(biāo)的標(biāo)簽欄,用戶可以擊內(nèi)部不同的圖標(biāo)切換屏幕中顯示的視圖,TableBarIOS只適用于IOS平臺
常用屬性
- barTintColor:標(biāo)簽欄的背景顏色
- tintColor:當(dāng)前被選中標(biāo)簽圖標(biāo)的顏色
- unselectedItemTintColor:當(dāng)前沒有被選中的標(biāo)簽圖標(biāo)的顏色
TabBarIOS.Item
TabBarIOS.Item是每個可以點擊標(biāo)簽不圖標(biāo),根據(jù)點擊的不同顯示不同的視圖
常用屬性
- title:在圖標(biāo)下面顯示的標(biāo)題文字
- icon:給當(dāng)前標(biāo)簽指定一個自定義的圖標(biāo)
- onPress:當(dāng)此標(biāo)簽被選中時調(diào)用。你應(yīng)該修改組件的狀態(tài)來使得
selected={true} - selected:這個屬性決定了子視圖是否可見。如果你看到一個空白的頁面,很可能是沒有選中任何一個標(biāo)簽。
代碼展示:
<TabBarIOS.Item
title=“movieTest”
icon={require(“./passport.png”)}
onPress={this.changeTab.bind(this, ”movieTest”)}
selected={this.state.selectTab == “movieTest”}
>
<MovieList></MovieList>
</TabBarIOS.Item>
示例
創(chuàng)建一個tabBar.js文件
代碼如下:
import React, { Component } from 'react';
import {
TabBarIOS
} from 'react-native';
//引入三個選項頁面(這里引入的是之前做好的幾個組件)
var Nav = require("./nav");
var MovieList = require("./movieList");
var ImageTest = require("./image");
var TabBarTest = React.createClass({
getInitialState:function () {
//顯示當(dāng)前顯示的標(biāo)簽
return {
selectTab: "首頁"
}
},
changeTab:function (name) {
this.setState({
selectTab:name
})
},
render:function () {
return (
<TabBarIOS barTintColor="#ccc"
tintColor={"red"}
unselectedItemTintColor={"cyan"}
>
{/*下部的標(biāo)簽欄*/}
<TabBarIOS.Item
title="首頁"
icon={require("./images/index.png")}
onPress={this.changeTab.bind(this,"首頁")}
selected={this.state.selectTab == "首頁"}
>
{/*每一個選項*/}
<Input/>
</TabBarIOS.Item>
<TabBarIOS.Item
title="圖片"
icon={require("./images/picture.png")}
onPress={this.changeTab.bind(this,"圖片")}
selected={this.state.selectTab == "圖片"}
>
{/*每一個選項*/}
<ImageTest/>
</TabBarIOS.Item>
<TabBarIOS.Item
title="電影"
icon={require("./images/movie.png")}
onPress={this.changeTab.bind(this,"電影")}
selected={this.state.selectTab == "電影"}
>
{/*每一個選項*/}
<MovieList/>
</TabBarIOS.Item>
</TabBarIOS>
)
}
});
module.exports = TabBarTest;
在index.ios.js文件中,代碼更改為如下:
import React, { Component } from 'react';
import {
AppRegistry,
View,
} from 'react-native';
var TabBarTest = require("./tabBar");
var TabTest = React.createClass({
render () {
return (
<View style={{flex: 1}}>
<TabBarTest></TabBarTest>
</View>
)
}
});
AppRegistry.registerComponent('useComponent', () => TabTest);
網(wǎng)絡(luò)請求
React Native提供了和web標(biāo)準(zhǔn)一致的Fetch API,用于滿足開發(fā)者訪問網(wǎng)絡(luò)的需求。與之前學(xué)過的AJAX很相似。
fetch()第一個參數(shù)為請求地址
fetch(‘https://mywebsite.com/mydata.json');
第二個參數(shù)可選,可以用來定制HTTP請求一些參數(shù)
fetch(‘https://mywebsite.com/endpoint/‘, {
method: ‘POST',
headers: {
‘Accept': ‘a(chǎn)pplication/json',
‘Content-Type': ‘a(chǎn)pplication/json',
},
body: JSON.stringify({
firstParam: ‘yourValue',
secondParam: ‘yourOtherValue',
})
})
其中body表示要傳輸?shù)臄?shù)據(jù)
Fetch 方法會返回一個Promise,需要對返回的數(shù)據(jù)進(jìn)行處理
通過鏈?zhǔn)浇Y(jié)構(gòu)添加then方法進(jìn)行成功數(shù)據(jù)處理
如果有錯,通過catch方式捕捉
getDate:function () {
fetch(url)
.then((res)=>{
return res.json();
})
.then((resData)=>{
this.setState({
loaded:true,
dataSource:this.state.dataSource.cloneWithRows(resData.data.movies)
})
})
.catch((err)=>{
alert(err)
})
}
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
hooks寫React組件的5個注意細(xì)節(jié)詳解
這篇文章主要為大家介紹了hooks寫React組件的5個需要注意的細(xì)節(jié)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
React中使用react-json-view展示JSON數(shù)據(jù)的操作方法
react-json-view是一個用于顯示和編輯javascript數(shù)組和JSON對象的React組件,本文給大家分享React中使用react-json-view展示JSON數(shù)據(jù)的操作方法,感興趣的朋友一起看看吧2023-12-12
React?高德地圖進(jìn)京證路線規(guī)劃問題記錄(匯總)
這篇文章主要介紹了React高德地圖進(jìn)京證路線規(guī)劃問題小記,本文通過實例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-08-08
使用react-native-doc-viewer實現(xiàn)文檔預(yù)覽
這篇文章主要介紹了使用react-native-doc-viewer實現(xiàn)文檔預(yù)覽,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
React路由規(guī)則定義與聲明式導(dǎo)航及編程式導(dǎo)航分別介紹
這篇文章主要介紹了React路由規(guī)則的定義、聲明式導(dǎo)航、編程式導(dǎo)航,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-09-09

