做Android的人都知道,Android有一种控件叫GridView,可以用来展示图片,类似于9宫格效果,而在react native中,我们要用FlatList实现这种效果~
sybil052-20180926-151732.pngFlatList属性
属性 | 作用 |
---|---|
horizontal | true 则变为水平布局模式 |
columnWrapperStyle | 如果设置了多列布局,则可以额外指定此样式作用在每行容器上 |
numColumns | 多列布局,此时组件内元素会从左到右从上到下按 Z 字形排列,类似启用了flexWrap的布局,但只能在非水平模式下使用 |
实现思路
sybil052-20180926-153034@2x.png如图,每行显示3个图片,总共有4个间隔,间隔距离我们给固定值,以此类推,如果显示cols个图片,间隔数为cols+1,我们需要据此计算图片宽度。
假设:列数cols = 3,左右边距left = 10, 上下间距top = 10,那么图片宽度ImageWH = (screenW - (cols + 1) * left) / cols,图片高度ImageH = ImageWH * 0.8
具体代码
import React, {PureComponent} from 'react';
import {connect} from 'react-redux';
import {
View,
StyleSheet,
FlatList,
Dimensions,
TouchableOpacity,
Image
} from 'react-native'
import Text from '../../components/common/scalingText';
import * as Color from '../../constants/colors';
import NavigationBar from '../../components/navigationBar/navigationBar';
const screenW = Dimensions.get('window').width;
// 一些常量设置
const cols = 3; // 列数
const left = 10; // 左右边距
const top = 10; // 上下边距
const ImageWH = (screenW - (cols + 1) * left) / cols; // 图片大小
class UploadInfo extends PureComponent {
constructor(props) {
super(props);
const params = this.props.navigation.state.params;
this.state={
title: params.title,
data:[
]
}
this.renderRow = this.renderRow.bind(this);
}
componentDidMount() {
}
// 返回cell
renderRow(rowData){
console.log('rowData',rowData)
return(
<TouchableOpacity
activeOpacity={0.8}
onPress={()=>{
this.props.navigation.push('ImageViewer',{
hideDelete: true,
image: this.state.data,
num: rowData.index,
});
}}
>
<View style={styles.innerViewStyle}>
<Image source={{uri:rowData.item.uri}} style={styles.iconStyle} />
</View>
</TouchableOpacity>
);
}
_keyExtractor = (item, index) => {
return item.uri + index
}
render() {
return (
<View style={styles.container}>
<NavigationBar
title={this.state.title}
hiddenBackIcon={false}
router={this.props.navigation}
/>
<FlatList
style={{backgroundColor: Color.WHITE_FFFFFF}}
renderItem={this.renderRow}
data={this.state.data}
keyExtractor={this._keyExtractor}
numColumns={cols}
columnWrapperStyle={styles.columnStyle}
horizontal={false}
/>
</View>
);
}
}
const styles =StyleSheet.create({
container: {
flex: 1,
backgroundColor: Color.GRAY_F0F2F5
},
columnStyle:{
// marginLeft: 10,
// marginRight: 10
},
innerViewStyle:{
width: ImageWH,
height: ImageWH * 0.8,
marginLeft: left,
marginTop: top,
// 文字内容居中对齐
alignItems:'center'
},
iconStyle:{
width: ImageWH,
height: ImageWH * 0.8,
},
});
function mapStateToProps(state){
return {};
}
function mapDispatchToProps (dispatch){
return {};
}
export default connect(mapStateToProps, mapDispatchToProps)(UploadInfo);