在ReactNative中,ListView就相當(dāng)于iOS中的UITableView则奥,但是相對(duì)于UITableView更加靈活一些狭园,比如,實(shí)現(xiàn)網(wǎng)格布局罚舱。網(wǎng)格布局的代碼如下:
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);
以上代碼運(yùn)行正常管闷,運(yùn)行結(jié)果如下:
但是如果將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添加點(diǎn)擊事件渐北,則布局就會(huì)出現(xiàn)問(wèn)題铭拧,運(yùn)行結(jié)果如下:
解決方法:給Touchable設(shè)置寬高