大家好我从json api获取数据,我使用flatlist来呈现项目.我使用numColumns属性每行显示3个项目 但我们假设我有7或8个项目 我在渲染方面遇到了麻烦.我想要显示的布局是这样的 X X XX X XX X 但我
但我们假设我有7或8个项目
我在渲染方面遇到了麻烦.我想要显示的布局是这样的
X X X X X X X X
但我得到的是这个:
layout
这是我的代码:
_renderItem = ({ item, index }) => ( <View style={categorystyles.Category} key={index}> <TouchableOpacity activeOpacity={.5} onPress={() => this.props.navigation.navigate('ListingPerCategory', { catid: item.id })}> {item.category_app_icon ? <Image style={categorystyles.CategoryImg} source={{ uri: `${item.category_app_icon}` }} /> : <Image style={categorystyles.CategoryImg} source={require('../assets/coffeecup.png')} />} </TouchableOpacity> <Text style={{ marginTop: 5 }}>{escape(item.name).replace('%20', ' ').replace('%26amp%3B%20', ' ')}</Text> </View> ) render(){ return( <FlatList horizontal={false} data={this.state.categories} keyExtractor={(item, index) => item.id} numColumns={3} renderItem={this._renderItem} /> ) } const styles = StyleSheet.create({ Category: { flex:1, justifyContent: 'center', alignItems:'center', margin:5 }, CategoryImg: { resizeMode: 'contain', width: 50, height: 50 } })由于您使用的是flex:1和alignItems:center,因此您的布局将如下所示
因此,其中的项目将根据项目布局对齐到垂直和水平居中.
相反,您需要检查设备的宽度并根据它添加布局.
在你的风格
Category: { flex:1, maxWidth: Dimensions.get('window').width / 3 - 10, // Width / 3 - (marginLeft and marginRight for the components) justifyContent: 'center', alignItems:'center', margin:5 },
添加此样式后,布局将如下所示