RN中有一个非常重要的组件—ListView。这是一个垂直滑动的组件,为了保证性能,ListView不会将子空间全部渲染,而是只加载手机屏幕中的可见的组件。这样保证了手机运行的流畅度。还是先看一段代码:
export default class Entrance extends Component {
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows([
'John', 'Joel', 'James', 'Jimmy', 'Jackson', 'Jillian', 'Julie', 'Devin'
])
};
}
render() {
var dataSource = this.state.dataSource;
return (
<ListView
dataSource={dataSource}
renderRow={this.renderEvalation}
/>
);
}
renderEvalation(data){
return(
<Text style = {styles.tv_name}>{data}</Text>
);
}
}
const styles= StyleSheet.create({
tv_name:{
fontSize:20,
color:"red",
backgroundColor:'yellow',
marginTop:10,
textAlign:'center'
},
});
运行结果:
代码比较简单,我们粗率的分析一下。ListView要显示数据,首先要有数据源。数据源并不是一个数组或者, ListView.DataSource实例,通过如下方式获取
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
要是直接用一个数组,是不显示的。renderRow属性为每一个item添加组件和数据,renderRow接受的是一个方法,返回值一共有四个(rowData, sectionID, rowID, highlightRow) ,这里我们只用了一个参数的方法。rowData也就是数据源的一条数据。这样数据就通过Text标签显示到ListView上了。 是不是感觉弱爆了?那么,我们稍微加一些难度,让数据三个一排,横向排列。简单修改一下代码,然后看效果。
//获取屏幕宽高
var Dimensions = require('Dimensions');
var ScreenWidth = Dimensions.get('window').width;
var ScreenHeight = Dimensions.get('window').height;
<ListView
dataSource={dataSource}
renderRow={this.renderEvalation}
contentContainerStyle={styles.lv_evaluation} />
const styles= StyleSheet.create({
tv_name:{
width:ScreenWidth/3,
height:40,
fontSize:20,
color:"red",
backgroundColor:'yellow',
marginTop:10,
textAlign:'center'
},
lv_evaluation:{
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'flex-start',
},
});
运行效果:
为listview添加了样式,将flexDirection 设置为横向排列,每一个item的宽设置为屏幕的三分之一,item的从左到右排。在为listview添加样式的时候不能使用style属性了,要使用contentContainerStyle,否则不起作用,这样一个横向列表就完成了。横向和竖向列表我们都完成了,但是少了最重要的一点。还没有为listview设置点击事件呢?再次修改代码
<ListView
dataSource={dataSource}
enderRow={this.renderEvalation.bind(this)}
contentContainerStyle={styles.lv_evaluation} />
renderEvalation(data,sectionID, rowID){
return(
<Text style = {styles.tv_name} onPress ={ () => this.clickItem(rowID)}>{data}</Text>
);
}
clickItem(rowID){
console.log("----------rowID-----"+rowID);
}
在lisitview中绑定了this,然后为Text添加点击事件,注意,这里我们 使用了renderRow三个参数的 回调方法,其中rowID就是item对应的position。 ListView的基本用法就是这些,像列表刷新等我会在接下来的博客中介绍。有什么问题,欢迎交流!