在iOS中 我們可以利用 UICollectionView 來制作九宮格欄類似的界面,下面介紹在RN 中 制作九宮格的方法:
1:如果不需要分組只是簡單九宮格 ,可以直接用 FlatList 實現(xiàn),先上效果圖:

image.png
代碼:
import React, {Component} from 'react';
import {StyleSheet, Text, View, Image, FlatList, TouchableHighlight, SectionList, Dimensions} from 'react-native';
const dimension = Dimensions.get('window')
class CellList extends Component {
constructor(props) {
super(props);
}
render() {
var theModel = this.props.itemModel
return (
<View style={styles.cellContainer}>
<Image
source={{uri: theModel.iconUrl}}
style={styles.cellImg}/>
<View
style={styles.cellTitleViewStyle}
>
<Text style={{padding:5.0}}>標題標題</Text>
<Text style={{padding:5.0}}>姓名:{theModel.key}</Text>
</View>
</View>
)
}
}
export default class TableListView extends Component<Props> {
_renderItem = ({item}) => (
<CellList
itemModel = {item}
/>
)
_headerItem = () =>(
<View style={styles.headerStyle}>
<Text
style={{fontSize:18.0}}
>我是一個標題</Text>
</View>
)
render() {
var theModel = {
key: 'Devin',
detailDes:'是的水電費水電費水電費水電費水電費水電費',
iconUrl:'https://img.52z.com/upload/news/image/20180212/20180212084623_32086.jpg'};
return (
<View>
<FlatList
renderItem={this._renderItem}
data={[theModel,theModel,theModel,theModel,theModel,theModel,theModel,theModel]}
numColumns={3}
keyExtractor={(item, index) => item + index}
ListHeaderComponent={this._headerItem}
/>
</View>
);
}
}
//樣式
const styles = StyleSheet.create({
headerStyle:{
marginTop:50.0,
marginBottom:10.0,
height:50.0,
justifyContent:'center',
backgroundColor:'lightgray'
},
cellContainer: {
//flex:1, // 空間平均分布
alignItems:'center',
width:dimension.width/3.0
},
cellTitleViewStyle:{
justifyContent: "center"
},
cellImg: {
width: 80,
height: 80,
borderRadius: 40.0,
},
})
重點:設置 numColumns 屬性,限定每一行顯示多少個。 還有要設置單個 欄目的 width, 比如我這里沒行3個,那就要設置 width:dimension.width/3.0 ,有看到網(wǎng)友說 設置 //flex:1, // 空間平均分布 就可以了, 但是用這種方法會造成 最后欄也居中的問題:如圖

image.png
2:如果我們需要分組的九宮格,那就只能使用:SectionList:效果圖

image.png
重點:要注意設置,contentContainerStyle={styles.sectionViewStyle} 手動布置item 的顯示方式,
//列表的布局樣式
sectionViewStyle: {
flexDirection: 'row',
flexWrap: 'wrap',
alignItems: 'flex-start',
},
這段代碼是關鍵
同時需要注意設置 ListHeaderComponent和ListFooterComponent 的 width 為 屏幕寬,不然會造成布局錯亂,網(wǎng)上也有另一種 使用 Map 實現(xiàn)的方法, 我沒能成功,就沒寫了。
初學者記錄,大神勿噴