RN中ListView的Grid布局及注意事项
2017-02-10 本文已影响338人
Dadada胖子
在ReactNative中,ListView就相当于iOS中的UITableView,但是相对于UITableView更加灵活一些,比如,实现网格布局。网格布局的代码如下:
import React, {Component} from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
ListView,
Image,
TouchableOpacity
} from 'react-native';
let Dimensions = require('Dimensions');
let {width, height} = Dimensions.get('window');
let shareData = require('./shareData.json').data;
let cols = 3;
let cellW = 90;
let cellH = 120;
let hMargin = (width - cellW * cols) / (cols + 1);
let vMargin = 8;
let ListViewDemoB = React.createClass({
getInitialState(){
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => (r1 !== r2)});
return {
dataSource: ds.cloneWithRows(shareData)
}
},
render() {
return (
<ListView dataSource={this.state.dataSource}
renderRow={this.renderRow}
contentContainerStyle={styles.listStyle}
/>
);
},
//cell
renderRow(rowData) {
return (
<View style={styles.cellStyle}>
<Image source={{uri: rowData.icon}} style={styles.iconStyle}/>
<Text>{rowData.title}</Text>
</View>
);
}
});
const styles = StyleSheet.create({
iconStyle: {
width: cellW,
height: cellW,
marginBottom:8
},
cellStyle: {
width: cellW,
height: cellH,
marginLeft: hMargin,
marginTop: vMargin,
alignItems:'center'
},
listStyle: {
flexDirection: 'row',
flexWrap: 'wrap',
}
});
AppRegistry.registerComponent('ListViewDemoB', () => ListViewDemoB);
以上代码运行正常,运行结果如下:
结果正常的截图但是如果将renderRow中的代码:
renderRow(rowData) {
return (
<View style={styles.cellStyle}>
<Image source={{uri: rowData.icon}} style={styles.iconStyle}/>
<Text>{rowData.title}</Text>
</View>
);
}
替换成成:
renderRow(rowData) {
return (
<TouchableOpacity activeOpacity={0.5}>
<View style={styles.cellStyle}>
<Image source={{uri: rowData.icon}} style={styles.iconStyle}/>
<Text>{rowData.title}</Text>
</View>
</TouchableOpacity>
);
}
即给cell添加点击事件,则布局就会出现问题,运行结果如下:
结果异常的截图解决方法:给Touchable设置宽高
解决方法