當我們要做一些列表 我想ListView是再適合不過的組件了 在RN里面算是一個核心組件,用于高效地顯示一個可以垂直滾動的變化的數(shù)據(jù)列表。
廢話不多說 開始來做吧
第一步
如果我們要做一個列表 那么我們先要做出 里面里面每個item吧
Item代碼如下:List.js
import React from 'react';
import {
StyleSheet,
Text,
View,
Image,
TouchableHighlight
} from 'react-native';
export default class List extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<TouchableHighlight
style={styles.tbox}
underlayColor='#fff'
onPress={()=>{}}>
<View style={styles.box}>
<Image source={{uri:this.props.src}} style={styles.img} />
<View style={styles.txt}>
<Text style={styles.title}>{this.props.title}</Text>
<Text style={styles.time}>{this.props.time} | {this.props.id}</Text>
</View>
</View>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
tbox:{
backgroundColor:'#f5f5f5',
},
box:{
flexDirection:'row',
padding:5,
borderBottomWidth:1,
borderColor:'#eee',
},
img:{
flex:3.8,
resizeMode:Image.resizeMode.contain,
height:100
},
txt:{
flex:6.2,
paddingLeft:8,
paddingRight:3,
},
title:{
lineHeight:22,
},
time:{
marginTop:30,
color:'#999'
}
});
很簡單 單個的item就做好了 它的樣子應該是這樣的

List
第二步
我們要開始做ListView了
新建一個文件叫Main.js
首先在我們在構(gòu)造函數(shù)里 定義我們的state
constructor(props) {
super(props);
this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource:this.ds,
}
}
然后我們要加載數(shù)據(jù) 一般加載數(shù)據(jù)我會在組件渲染完成后執(zhí)行也就是componentDidMount里面 這里載入數(shù)據(jù)的我用的是fetch 代碼如下:
componentDidMount() {
fetch('http://ued.yihaodian.com:3001/api/70')
.then((response) => response.json())
.then((data) => {
this.setState({
dataSource:this.ds.cloneWithRows(data.listData)
})
})
.done();
}
數(shù)據(jù)應該長這樣:

api data
后面就是把List模塊渲染到ListView里面去了
rendList(data){
return (
<List
src={data.src}
title={data.title}
time={data.time}
id={data.id} />
)
}
...
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.rendList} />
);
}
最終效果圖:

Paste_Image.png
那么一個簡單的ListView的實例就完成了
后面我會講一下ListView如何實現(xiàn)下拉時動態(tài)渲染數(shù)據(jù)